[英]Referencing attribute value in xsl:param xsl:if test condition
我試圖從xsl:param檢索屬性值,並在xsl:if測試條件中使用它。 所以給定以下xml
<product>
<title>The Maze / Jane Evans</title>
</product>
和xsl
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="test" select="Jane"/>
<xsl:template match="title[contains(., (REFERENCE THE SELECT ATTRIBUTE IN PARAM))]">
<h2>
<xsl:value-of select="substring-before(., '/')"/>
</h2>
<p>
<xsl:value-of select="substring-after(., '/')"/>
</p>
</xsl:template>
<xsl:template match="title">
<h2><xsl:value-of select="."/></h2>
</xsl:template>
</xsl:stylesheet>
我想回來
The Maze
Jane Evans
您在這一行有問題 :
<xsl:param name="test" select="Jane"/>
這定義了一個名為test
的xsl:param
,其值是名為Jane
的當前節點('/')的子元素。 由於頂部元素是<product>
而不是<Jane>
,因此test
參數具有空節點集的值(以及字符串值-空字符串)。
您需要 (注意周圍的撇號):
<xsl:param name="test" select="'Jane'"/>
整個處理任務可以很容易地實現 :
此XSLT 1.0轉換 :
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pTest" select="'Jane'"/>
<xsl:template match="title">
<xsl:choose>
<xsl:when test="contains(., $pTest)">
<h2>
<xsl:value-of select="substring-before(., '/')"/>
</h2>
<p>
<xsl:value-of select="substring-after(., '/')"/>
</p>
</xsl:when>
<xsl:otherwise>
<h2><xsl:value-of select="."/></h2>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
當應用於提供的XML文檔時 :
<product>
<title>The Maze / Jane Evans</title>
</product>
產生想要的正確結果 :
<h2>The Maze </h2>
<p> Jane Evans</p>
說明 :
XSLT 1.0語法禁止以匹配模式引用變量/參數。 這就是為什么我們有一個與任何title
匹配的模板,並且在模板內指定了以特定的所需方式進行處理的條件的原因。
XSLT 2.0解決方案 :
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pTest" select="'Jane'"/>
<xsl:template match="title[contains(., $pTest)]">
<h2>
<xsl:value-of select="substring-before(., '/')"/>
</h2>
<p>
<xsl:value-of select="substring-after(., '/')"/>
</p>
</xsl:template>
<xsl:template match="title">
<h2><xsl:value-of select="."/></h2>
</xsl:template>
</xsl:stylesheet>
當此轉換應用於提供的XML文檔(如上)時,同樣會產生所需的正確結果 :
<h2>The Maze </h2>
<p> Jane Evans</p>
說明 :
XSLT 2.0沒有XSLT 1.0的限制,並且可以在匹配模式中使用變量/參數引用。
術語$ test是指測試參數的值。 使用$ test
例如:
<xsl:template match="title[contains(., $test)]">
<h2>
<xsl:value-of select="substring-before(., '/')"/>
</h2>
<p>
<xsl:value-of select="substring-after(., '/')"/>
</p>
</xsl:template>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.