Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...