2009-02-26 30 views
6

我發現無法使用-param來使用應用程序模板。作爲一個例子,我已經破解了w3schools中給出的例子。爲什麼我無法使用參數在XSL中使用apply-templates?

XSL

<xsl:template match="/"> 
    <xsl:apply-templates> 
    <xsl:with-param name="test" select="'has this parameter been passed?'"/> 
    </xsl:apply-templates> 
</xsl:template> 

<xsl:template match="cd"> 
    <xsl:param name="test"></xsl:param> 
    parameter: 
    <xsl:value-of select="$test"></xsl:value-of> 
</xsl:template> 

XML

<catalog> 
    <cd> 
    <title>Empire Burlesque</title> 
    <artist>Bob Dylan</artist> 
    <country>USA</country> 
    <company>Columbia</company> 
    <price>10.90</price> 
    <year>1985</year> 
    </cd> 
    <cd> 
    <title>Hide your heart</title> 
    <artist>Bonnie Tyler</artist> 
    <country>UK</country> 
    <company>CBS Records</company> 
    <price>9.90</price> 
    <year>1988</year> 
    </cd> 
</catalog> 

(希望),你會看到,測試參數沒有被傳遞到CD模板。使用呼叫模板時可以使用它,但不能使用應用模板。這是怎麼回事?我正在使用XSL 1.0。請忽略我傳遞硬編碼參數的事實 - 這僅僅是一個例子。

回答

5

嗯...有趣......我無法用XslTransformXslCompiledTransform在.NET中 - 但它看起來像它應該工作...好奇...

更新問題看起來是匹配;嘗試

<xsl:template match="/catalog"> <!-- CHANGE HERE --> 
    <xsl:apply-templates> 
    <xsl:with-param name="test" select="'has this parameter been passed?'"/> 
    </xsl:apply-templates> 
</xsl:template> 

然後,這對我沒有任何其他變化。不同之處在於您正在匹配根節點。當你做了「申請模板」時,它將級聯第一個到目錄(與參數),然後到cd(沒有參數)。爲了得到你想要的東西,你需要從目錄開始。你可以通過在比賽中添加一個<xsl:vaue-of select="name()"/>來查看,然後將其作爲「/」和「/ catalog」來使用。

2

嘗試指定模板適用於:

<xsl:template match="/"> 
    <xsl:apply-templates select="catalog/cd"> 
    <xsl:with-param name="test" select="'has this parameter been passed?'"/> 
    </xsl:apply-templates> 
</xsl:template> 
+0

沒趕不上 - 試試這個解決方案。似乎有些東西在沒有指定模板路徑時出錯。 – Goran 2009-02-26 11:58:16

+0

是的,你是對的。無論如何,我相信選擇中的//是糟糕的形式。而且,這個雙斜線似乎是傳遞參數的關鍵。在我的真實代碼中,我已經在select中傳遞了一個節點,但是,該參數僅在使用//爲節點添加前綴後才被傳遞。爲什麼? – darasd 2009-02-26 12:03:33

+0

好吧 - 現在這是行爲奇怪 - 這個問題沒有4個答案也編輯得到顯示,然後隨機丟失... – Goran 2009-02-26 12:04:27

0

對我的作品與1.1.24的libxslt從http://xmlsoft.org/XSLT/

$ xsltproc xml1.xsl xml1.xml 
<?xml version="1.0"?> 


    parameter: 
    has this parameter been passed? 

    parameter: 
    has this parameter been passed? 
0

我看到的問題是,根目錄下有cd元素沒有匹配。在根你有目錄元素不是CD元素,所以修改模板匹配=「目錄」

2

你總是可以使用XSL去:調用模板..如:

... 
<xsl:call-template name="foo"> 
    <xsl:with-param name="bars" select="42"/> 
</xsl:call-template> 
... 

<xsl:template name="foo"> 
    <xsl:param name="bars"/> 
    <xsl:value-of select="$node"/> 
</xsl:template> 
相關問題