1

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?

2
  • If you want to write a transformation to producing appallingly designed XML, you will find more friends if you explain that you know it's appalling XML but you have good reasons for doing it.... Commented Oct 28, 2014 at 20:49
  • It is a good point. I do know that the target XML design is appallingly bad, but it's for integration with a legacy system that was designed by trolls. My initial XML design is the one I'm working with in code; this transformation step is the last mile. Commented Oct 29, 2014 at 0:21

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Regarding "good idea": quite right. I've added a disclaimer in the question. I will try this out in the morning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.