2009-02-26 33 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> 
相关问题