2011-01-13 70 views
14

我遇到問題xsl:variable。我想創建一個值取決於另一個XML節點屬性的值的變量。這工作很好。但是,當我嘗試使用表示XPath的字符串值創建變量時,它只是在我嘗試將它用作稍後XSL標記中的XPath時不起作用。xsl:變量爲其他xsl標記的xpath值

<xsl:variable name="test"> 
    <xsl:choose> 
    <xsl:when test="node/@attribute=0">string/represent/xpath/1</xsl:when> 
    <xsl:otherwise>string/represent/xpath/2</xsl:otherwise> 
    </xsl:choose>  
</xsl:variable>     
<xsl:for-each select="$test"> 
    [...] 
</xsl:for-each> 

我想: How to use xsl variable in xsl iftrouble with xsl:for-each selection using xsl:variable。但沒有結果。

回答

10

如果這些路徑是事先這樣的情況下知道,那麼你可以使用:

<xsl:variable name="vCondition" select="node/@attribute = 0"/> 
<xsl:variable name="test" select="actual/path[$vCondition] | 
            other/actual/path[not($vCondition)]"/> 
+0

謝謝。這不正是我所要求的,但它正是我需要的) – 2011-01-13 17:53:16

10

XPath表達式的動態評估通常不在XSLT支持(1.0和2.0),但是:

我們可以實現一個比較一般的動態XPath計算器,如果我們只限制各位置路徑是一個元件命名

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="text"/> 

<xsl:param name="inputId" select="'param/yyy/value'"/> 

<xsl:variable name="vXpathExpression" 
    select="concat('root/meta/url_params/', $inputId)"/> 

<xsl:template match="/"> 
    <xsl:value-of select="$vXpathExpression"/>: <xsl:text/> 

    <xsl:call-template name="getNodeValue"> 
    <xsl:with-param name="pExpression" 
     select="$vXpathExpression"/> 
    </xsl:call-template> 
</xsl:template> 

<xsl:template name="getNodeValue"> 
    <xsl:param name="pExpression"/> 
    <xsl:param name="pCurrentNode" select="."/> 

    <xsl:choose> 
    <xsl:when test="not(contains($pExpression, '/'))"> 
     <xsl:value-of select="$pCurrentNode/*[name()=$pExpression]"/> 
    </xsl:when> 
    <xsl:otherwise> 
     <xsl:call-template name="getNodeValue"> 
     <xsl:with-param name="pExpression" 
      select="substring-after($pExpression, '/')"/> 
     <xsl:with-param name="pCurrentNode" select= 
     "$pCurrentNode/*[name()=substring-before($pExpression, '/')]"/> 
     </xsl:call-template> 
    </xsl:otherwise> 
    </xsl:choose> 
</xsl:template> 
</xsl:stylesheet> 

當這一轉型是這個XML文檔施加:

<root> 
    <meta> 
    <url_params> 
     <param> 
     <xxx> 
      <value>5</value> 
     </xxx> 
     </param> 
     <param> 
     <yyy> 
      <value>8</value> 
     </yyy> 
     </param> 
    </url_params> 
    </meta> 
</root> 

的希望,正確的結果產生

root/meta/url_params/param/yyy/value: 8 
+0

+1。看上去挺有趣。 – Flack 2011-01-13 20:13:03