I have nested xsl:for loops:
<xsl:for-each select="/Root/A"> <xsl:for-each select="/Root/B"> <!-- Code --> </xsl:for> </xsl:for>
From within the inner loop, how can I access attributes from the current node in the outer loop?
I keep finding myself writing code like this:
<xsl:for-each select="/Root/A"> <xsl:variable name="someattribute" select="@SomeAttribute"/> <xsl:for-each select="/Root/B"> <!-- Now can use $someattribute to access data from 'A' --> </xsl:for> </xsl:for>
This doesn't scale very well, as sometimes I need to access several pieces of information and end up creating one variable for each piece. Is there an easier way?
Technically the correct answer is to label the outer loop. In practice if you want to exit at any point inside an inner loop then you would be better off externalizing the code into a method (a static method if needs be) and then call it. That would pay off for readability.
A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes.
A nested loop is a (inner) loop that appears in the loop body of another (outer) loop. The inner or outer loop can be any type: while, do while, or for. For example, the inner loop can be a while loop while an outer loop can be a for loop. Of course, they can be the same kind of loops too.
You can store the entire /Root/A structure in a variable, and make reference to that variable rather than creating a new variable for every attribute and subelement you need to access.
<xsl:for-each select="/Root/A/"> <xsl:variable name="ROOT_A" select="."/> <xsl:for-each select="/Root/B/"> <!-- Variable is accessed like this: $ROOT_A/@someAttribute Just like a normal XML node --> </xsl:for-each> </xsl:for-each>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With