我正在尝试在XSL中为变量赋值:for-each并在XSL:for-loop结束后(或者甚至在它移动到下一个XSL:for-each之后)访问变量。我尝试过使用全局变量和局部变量,但似乎没有用。
这可能吗?如果没有,还有另一种解决方法吗?
-Hammer
答案 0 :(得分:2)
我正在尝试给变量一个值 在XSL中:for-each并访问 XSL之后的变量:for-loop有 结束了(甚至在它搬到了之后 下一个XSL:for-each)
不,这是不可能的。有很多方法,但哪一个最好取决于你想做什么。
有关详细说明,请参阅this very similar question。同样read this thread,因为它也是密切相关的。
答案 1 :(得分:1)
我找到的唯一方法就是使用call-template并将你的" for-each"的结果作为参数发送。
<?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来扫描项目节点和每个配置文件节点的依赖关系。注册&#34;节点&#34;我使用参数$ profile,当我解析依赖循环时,我用它来检索配置文件&#34; id&#34;。
注意:parseContent不在这里,但它用于解析maven参数。
答案 2 :(得分:0)
XSLT变量是不可变的(不能更改)并且严格限定范围。
您始终可以使用xsl:for-each
打包xsl:variable
。 xsl:for-each
中发出的任何文字值都将分配给xsl:variable
。
例如,以下样式表声明了变量textValueCSV
。在xsl:for-each
内
它使用xsl:value-of
和xsl: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