如何从嵌套循环中访问外部循环中的元素? [英] How do I access elements from the outer loop from within nested loops?

查看:148
本文介绍了如何从嵌套循环中访问外部循环中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < xsl:for-each select =/ Root / A > 
< xsl:for-each select =/ Root / B>
<! - Code - >
< / xsl:for>
< / xsl:for>

在内部循环中,如何从外部当前节点访问属性循环?



我一直在发现自己写这样的代码:

 < xsl:for-each select =/ Root / A> 
< xsl:for-each select =/ Root / B>
<! - 现在可以使用$ someattribute来访问'A'中的数据 - >
< / xsl:for>
< / xsl:for>

这并不是很好,因为有时我需要访问几条信息,为每件创建一个变量。有没有更简单的方法?

解决方案

您可以将整个/ Root / A结构存储在一个变量中,并引用变量,而不是为每个需要访问的属性和子元素创建一个新变量。

 < xsl:for-each select = /根/ A / > 
< xsl:variable name =ROOT_Aselect =。/>
<! - 变量是这样访问的:$ ROOT_A / @ someAttribute
就像普通的XML节点 - >
< / xsl:for-each>
< / xsl:for-each>


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?

解决方案

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>

这篇关于如何从嵌套循环中访问外部循环中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆