Reputation: 3961
I'm trying to use XSLT to transform this:
<Parents>
<Parent>
<ChildA val="bill" />
<ChildB val="tom" />
</Parent>
<Parent>
<ChildA val="jake" />
<ChildB val="sue" />
</Parent>
</Parents>
into this:
<Parents>
<ChildA1 val="bill" />
<ChildB1 val="tom" />
<ChildA2 val="jake" />
<ChildB2 val="sue" />
</Parents>
<DISCLAIMER> The target XML is not the shape I would choose for any purpose, except for integration with a system designed by sadistic trolls. Unfortunately, I am now faced with one of those (a system, that is; not a troll).</DISCLAIMER>
I'm starting with complex-valued elements, and I need to merge their children into a single long list. Numbers are used to distinguish the children from each other.
I know that XSLT can be used to transform a single <Parent>
element to its two Child elements. Is there a way I could leverage a counter from the XSLT transformer to automatically do the number appending?
Upvotes: 1
Views: 1096
Reputation: 167716
Well if you use xsl:number
as in
<xsl:template match="Parents/Parent/*">
<xsl:variable name="index"><xsl:number level="any"/></xsl:variable>
<xsl:element name="{name()}{$index}">
<xsl:copy-of select="@* | node()"/>
</xsl:element>
</xsl:template>
you can construct element names with a number counting the elements of the same name on different levels but usually with XML it is not a good idea to put an index number in an element name, if you really want an index then put it into an attribute or child element dedicated to that purpose.
Upvotes: 4