2010-10-17 85 views
1

我试图在XSL中为变量提供一个值:for-each并在XSL:for-loop结束后访问该变量(或者甚至在它移动到下一个XSL:for-each之后)。我试过使用全局和局部变量,但他们似乎并没有工作。从XSL内部传递一个变量:for-each到XSL外部:for-each

这可能吗?如果没有,是否有另一种解决问题的方法?

-Hammer

+0

请提供您的XML和XSLT代码(最低限度),并更好地解释问题所在。然后,许多读者将能够向您展示解决方案。至于你的一般问题,答案是否定的,正如@Tomalak和@ Mads-Hansen所解释的那样。 – 2010-10-17 14:53:34

回答

2

我试图给一个变量的值 XSL中:对,每个和XSL后访问 变量:for循环已经结束 (或者它转移到即使 next XSL:for-each)

不,这是不可能的。有办法绕过它,但哪一个最好取决于你想要做什么。

有关详细说明,请参阅this very similar question。也是read this thread,因为它也是密切相关的。

0

XSLT变量是不可变的(不能被改变)并且被严格限定范围。

您总是可以用xsl:variable包装xsl:for-each。在xsl:for-each内发出的任何文本值将被分配到xsl:variable

例如,以下样式表声明变量textValueCSV。在xsl:for-each 它使用xsl:value-ofxsl:text。所有文本值都分配给变量textValuesCSV用于xsl:for-each以外的以选择它的值。

<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:output method="text" /> 

<xsl:template match="/"> 

    <xsl:variable name="textValuesCSV"> 
     <xsl:for-each select="/*/*"> 
      <xsl:value-of select="."/> 
      <xsl:if test="position()!=last()"> 
       <xsl:text>,</xsl:text> 
      </xsl:if> 
     </xsl:for-each> 
    </xsl:variable> 

    <xsl:value-of select="$textValuesCSV"/> 

</xsl:template> 

</xsl:stylesheet> 

当应用到这个XML:

<doc> 
    <a>1</a> 
    <b>2</b> 
    <c>3</c> 
</doc> 

产生这样的输出:

1,2,3 
1

唯一的办法,我发现是使用调用模板和发送作为参数的时结果你的“每一个”。

<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:mvn="http://maven.apache.org/POM/4.0.0"> 
    <xsl:variable name="project" select="/mvn:project" /> 

    <xsl:template name="parseDependencies"> 
    <xsl:param name="profile" /> 
    <xsl:for-each select="$profile/mvn:dependencies/mvn:dependency"> 
     <dependency> 
      <xsl:attribute name="profile"> 
      <xsl:value-of select="$profile/mvn:id" /> 
      </xsl:attribute> 
      <xsl:for-each select="mvn:*[node()]"> 
      <xsl:element name="{name(.)}"> 
       <xsl:call-template name="parseContent"> 
       <xsl:with-param name="text" select="text()" /> 
       </xsl:call-template> 
      </xsl:element> 
      </xsl:for-each> 
     </dependency> 
    </xsl:for-each> 
    </xsl:template> 

    <xsl:template match="mvn:project"> 
     <dependencies> 
     <xsl:call-template name="parseDependencies"> 
      <xsl:with-param name="profile" select="." /> 
     </xsl:call-template> 
     <xsl:for-each select="mvn:profiles/mvn:profile"> 
      <xsl:call-template name="parseDependencies"> 
      <xsl:with-param name="profile" select="." /> 
      </xsl:call-template> 
     </xsl:for-each> 
     </dependencies> 
    </xsl:template> 
</xsl:stylesheet> 

这里我调用Maven项目(pom.xml)中的parseDependencies来扫描项目节点和每个配置文件节点中的依赖关系。要注册“节点”,我使用参数$ profile,当我解析依赖性循环时,我用它来检索配置文件“id”。

注意:parseContent不在这里,但它用来解析maven参数。