2017-06-01 70 views
2

我錯過了什麼概念,我沒有得到我期待的內容?另外,爲什麼在匹配第二次時@field會變成空白(不顯示「位置」)?xslt呼叫模板不像我期望的那樣行事

XSL

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="1.0"> 

    <xsl:output method="text"/> 

    <!-- sample XSLT snippet --> 
    <xsl:template match="xml"> 
    <xsl:apply-templates select="*" /> 
    <!-- three nodes selected here --> 
    <xsl:call-template name="rshandle" /> 

    </xsl:template> 

    <xsl:template match="foo"> 
    <!-- will be called once --> 
    <xsl:text> 
     foo element encountered 
    </xsl:text> 
    </xsl:template> 

    <xsl:template match="*"> 
    <!-- will be called twice --> 
    <xsl:text> 
     other element ecountered 
    </xsl:text> 
    </xsl:template> 


    <xsl:template name="rshandle" match="foo"> 
    <!-- will be called once --> 
    <xsl:value-of select="@field" /> 
    <xsl:text> 
     oops i did it again! 
    </xsl:text> 
    </xsl:template> 

</xsl:stylesheet> 

XML

<?xml version="1.0" encoding="utf-8"?> 
<?xml-stylesheet type="text/xsl" href="calltemplatematch.xslt"?> 
<!-- sample XML snippet --> 
<xml> 
    <foo field="location"/> 
    <bar /> 
    <baz /> 
</xml> 

期待

 other element ecountered 

     other element ecountered 

location 
     oops i did it again! 

實際

location 
     oops i did it again! 

     other element ecountered 

     other element ecountered 

     oops i did it again! 
+0

你需要解釋哪部分? –

+0

我更新了OP,做得更具體。我想對於初學者來說,爲什麼@field在底部出現的第二個實例上是空的(而不是顯示位置字符串)? – Rod

+0

恐怕您需要針對您不瞭解的每件商品提出具體問題。 –

回答

1

爲了滿足您的期望,XSL應該是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 

    <xsl:output method="text"/> 

    <!-- sample XSLT snippet --> 
    <xsl:template match="xml"> 
     <xsl:apply-templates select="*"/> 
     <!-- three nodes selected here --> 
     <xsl:apply-templates select="foo" mode="rshandle"/> 
    </xsl:template> 

    <xsl:template match="foo"/> 

    <xsl:template match="*"> 
     <!-- will be called twice --> 
     <xsl:text>other element ecountered</xsl:text> 
    </xsl:template> 

    <xsl:template match="foo" mode="rshandle"> 
     <!-- will be called once --> 
     <xsl:value-of select="@field"/> 
     <xsl:text>oops i did it again!</xsl:text> 
    </xsl:template> 

</xsl:stylesheet> 

另外,爲什麼會@field是空白(不顯示「位置」)周圍配套的第2次是什麼時候?

因爲您使用了<xsl:call-template>another answer的好解釋:

用XSLT理解的概念是「當前節點」的概念。使用<xsl:apply-templates>,當前節點每次迭代都會繼續,而<xsl:call-template>不會更改當前節點。即被叫模板中的.指的是與呼叫模板中的.相同的節點。 apply-templates並非如此。

1

爲什麼@field空白的出現在底部的第二個實例?

因爲當「rshandle」模板是稱爲,它是從xml根元素的上下文中調用 - 這不具有field屬性。 調用模板不會更改當前上下文 - 不像應用模板。

相關問題