Aniket V
Aniket V

Reputation: 3247

Using <xsl:for-each> for incremental element names

I have an XML that is converted from a java map. So all the map keys are converted into node names. The XML structure is as below

<map>
    <firstName>AAA</firstName>
    <firstName1>BBB</firstName1>
    <firstName2>CCC</firstName2>
    <firstName3>DDD</firstName3>
</map>

I am trying to write a for-each loop to extract data from this XML to create an output XML. I have tried most of the options available such as name(), local-name(), contains(), etc but couldn't come up with something that worked. What are the options available since the incremental node name can go upto count 100 or more. Any inputs in coding the loop would be of great help. I am using XSLT 1.0.

Upvotes: 1

Views: 1443

Answers (2)

RRitter
RRitter

Reputation: 11

This will select all the first level elements and their information, which you can then use as you wish:

<xsl:for-each select="/*/*">
    <xsl:value-of select="local-name()"/>
    <xsl:value-of select="."/>
</xsl:for-each>

Upvotes: 1

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

There are many ways to select the children of the top element (map):

/*/*

This selects all elements that are children of the top element of the XML document.

/*/*[starts-with(name(), 'firstName')]

This selects all top element's children-elements, whose name starts with the string 'firstName'.

/*/*[starts-with(name(), 'firstName') 
   and floor(substring-after(name(), 'firstName')) = substring-after(name(), 'firstName')) ]

This selects all top element's children-elements, whose name starts with the string 'firstName' and the remaining substring after this is an integer.

/*/*[starts-with(name(), 'firstName') 
   and translate(name(), '0123456789', '') = 'firstName')) ]

This selects all top element's children-elements, whose name starts with the string 'firstName' and the remaining substring after this contains only digits.

Finally, in XPath 2.0 (XSLT 2.0) one can use regular expressions:

/*/*[matches(name(), '^firstName\d+$')]

Upvotes: 2

Related Questions