Move sub nodes into parent attributes with XSLT

后端 未结 2 1037
臣服心动
臣服心动 2021-01-06 15:07

I have some XML which contains records and sub records, like this:


    

        
相关标签:
2条回答
  • 2021-01-06 15:45

    This might do it, run this following snippet of XSLT when processing the top level <record> elements:

    <xsl:for-each select="record">
        <xsl:attribute name="{position()}">
            <xsl:value-of select="@string" />
        </xsl:attribute>
    </xsl:for-each>
    

    Essentially this iterates over each sub-<record> element and creates an <xsl:attribute> element describing the desired attribute. The position() function is called to get the relative position within the top level element: 1, 2, 3, etc.

    This is not a complete solution; some familiarity with XSLT is assumed.

    0 讨论(0)
  • 2021-01-06 15:53

    Here's a complete solution:

    <xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <!-- By default, recursively copy all nodes unchanged -->
      <xsl:template match="@* | node()">
        <xsl:copy>
          <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
      </xsl:template>
    
      <!-- But don't process any children of <record> (such as whitespace)... -->
      <xsl:template match="record/node()"/>
    
      <!-- ...except for doubly-nested records;
           convert them to attributes, named according to position -->
      <xsl:template match="record/record" priority="1">
        <xsl:variable name="pos">
          <xsl:number/>
        </xsl:variable>
        <xsl:attribute name="r{$pos}">
          <xsl:value-of select="@string"/>
        </xsl:attribute>
      </xsl:template>
    
    </xsl:stylesheet>
    

    Note that I changed the name of your attributes to "r1", "r2", etc., because XML doesn't allow you to start a name with a number.

    0 讨论(0)
提交回复
热议问题