Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access elements from the outer loop from within nested loops?

Tags:

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?

like image 326
pauldoo Avatar asked Jan 17 '09 12:01

pauldoo


People also ask

How do you break the outer for loop from the inner loop?

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.

How do you run a loop within a loop?

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.

What is outer and inner loop?

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.


1 Answers

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> 
like image 57
Welbog Avatar answered Oct 10 '22 05:10

Welbog