Using this input XML:
<?xml version="1.0" encoding="utf-8"?>
<Employees>
<Employee ID="1">
<FirstName>Klaus</FirstName>
<LastName>Salchner</LastName>
</Employee>
<Employee ID="2">
<FirstName>Peter</FirstName>
<LastName>Pan</LastName>
</Employee>
</Employees>
How would you get this output:
<Employees>
<FirstName>
<Employee>Klaus</Employee>
<Employee>Peter</Employee>
</FirstName>
<LastName>
<Employee>Salchner</Employee>
<Employee>Pan</Employee>
</LastName>
</Employees>
But, if you don’t know how many fields there are going to be in the Employee elements – however, lets assume that the same elements (here being, FirstName and LastnName) will definately be present in every Employee element.
The best I’ve got is:
<Employees>
<xsl:for-each select="*/Employee/.">
<xsl:value-of select=".">
<xsl:value-of select="./." />
</xsl:value-of>
</xsl:for-each>
</Employees>
And I know that’s wrong!
Well, I worked it out in the end – basically I need a for-each for the elements in the first Employee and assign a variable inside the for-each to the position() value.
Then, in a second, nested for-each, I loop through the outer Employee elements.
For each Employee element I use the variable (which contains the “row” of the inner element) to index it’s inner element.
Something like:
I will admit, mine is a little more concise, but that’s the gist.
In short (deep breath) loop through the list of elements of the first outer element. For each one, loop through the outer elements and use the index of the inner elements to pick the inner elements sequentially.