我試圖在XSL中爲變量提供一個值:for-each並在XSL:for-loop結束後訪問該變量(或者甚至在它移動到下一個XSL:for-each之後)。我試過使用全局和局部變量,但他們似乎並沒有工作。從XSL內部傳遞一個變量:for-each到XSL外部:for-each
這可能嗎?如果沒有,是否有另一種解決問題的方法?
-Hammer我試圖在XSL中爲變量提供一個值:for-each並在XSL:for-loop結束後訪問該變量(或者甚至在它移動到下一個XSL:for-each之後)。我試過使用全局和局部變量,但他們似乎並沒有工作。從XSL內部傳遞一個變量:for-each到XSL外部:for-each
這可能嗎?如果沒有,是否有另一種解決問題的方法?
-Hammer我試圖給一個變量的值 XSL中:對,每個和XSL後訪問 變量:for循環已經結束 (或者它轉移到即使 next XSL:for-each)
不,這是不可能的。有辦法繞過它,但哪一個最好取決於你想要做什麼。
有關詳細說明,請參閱this very similar question。也是read this thread,因爲它也是密切相關的。
XSLT變量是不可變的(不能被改變)並且被嚴格限定範圍。
您總是可以用xsl:variable
包裝xsl:for-each
。在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
唯一的辦法,我發現是使用調用模板和發送作爲參數的時結果你的「每一個」。
<?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參數。
請提供您的XML和XSLT代碼(最低限度),並更好地解釋問題所在。然後,許多讀者將能夠向您展示解決方案。至於你的一般問題,答案是否定的,正如@Tomalak和@ Mads-Hansen所解釋的那樣。 – 2010-10-17 14:53:34