[英]XSLT - arrays and iterations
如何創建數組並遍歷數組並獲取其值?
例:
<xsl:variable name="element">
<xsl:for-each select="document/items/item">
<item>
<xsl:choose>
<xsl:when test="/@attr">1</xsl:when>
<xsl:otherwise>0</xsl:otherwise>
</xsl:choose>
</item>
</xsl:for-each>
</xsl:variable>
<xsl:for-each select="$element">
<p><xsl:value-of select="."/></p>
</xsl:for-each>
實際輸出:
<p>0100</p>
應該:
<p>0</p>
<p>1</p>
<p>0</p>
<p>0</p>
編輯:數組應該動態生成!
給定
<xsl:variable name="element">
<xsl:for-each select="document/items/item">
<item>
<xsl:choose>
<xsl:when test="/@attr">1</xsl:when>
<xsl:otherwise>0</xsl:otherwise>
</xsl:choose>
</item>
</xsl:for-each>
</xsl:variable>
和XSLT 1.0處理器,您的變量是結果樹片段類型,您所能做的就是使用<xsl:copy-of select="$element"/>
或<xsl:value-of select="$element"/>
或您需要使用諸如exsl:node-set
類的擴展功能將結果樹片段轉換為節點集,因此
<xsl:for-each select="exsl:node-set($element)/item">
<p><xsl:value-of select="."/></p>
</xsl:for-each>
應該這樣做(使用樣式表中聲明的xmlns:exsl="http://exslt.org/common"
)。
在XSLT 2.0或3.0中,您的變量是一個臨時樹,其根節點包含一些item
元素,因此您不需要擴展功能,但需要解決item
元素,例如
<xsl:for-each select="$element/item">
<p><xsl:value-of select="."/></p>
</xsl:for-each>
作為XSLT 2.0 / 3.0中的替代方法,您可以將變量聲明更改為
<xsl:variable name="element" as="element(item)*">
<xsl:for-each select="document/items/item">
<item>
<xsl:choose>
<xsl:when test="/@attr">1</xsl:when>
<xsl:otherwise>0</xsl:otherwise>
</xsl:choose>
</item>
</xsl:for-each>
</xsl:variable>
具有一個包含一系列item
元素的變量,在這種情況下,
<xsl:for-each select="$element">
<p><xsl:value-of select="."/></p>
</xsl:for-each>
會做你想要的。
XSLT 1.0或2.0中沒有數組。
@Pali,
請共享需要轉換的XML。 我會幫你的 。
XSL:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<xsl:for-each select="document/items/item">
<item>
<xsl:choose>
<p>
<xsl:when test="/@attr">1</xsl:when>
<xsl:otherwise>0</xsl:otherwise>
</p>
</xsl:choose>
</item>
</xsl:for-each>
</xsl:variable>
</xsl:template>
</xsl:stylesheet>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.