2013-10-02 21 views
2

我有這一脈的頂級元素的XML:nodeset測試不一致?

<chapter template="one"/> 
<chapter template="two"/> 
<chapter template="one"/> 
<chapter template="one"/> 
<chapter template="two"/> 
<chapter template="one"/> 

我通過它們與選擇的語句循環處理這些元素:

<xsl:variable name="layout" select="@template"/> 
<xsl:choose> 
    <xsl:when test="contains($layout, 'one')"> 
     <xsl:call-template name="processChapterOne"/> 
    </xsl:when> 
    <xsl:when test="contains($layout, 'two')"> 
     <xsl:call-template name="processChaptertwo"/> 
    </xsl:when> 
<xsl:otherwise/> 
</xsl:choose> 

這正常工作。但現在我試圖做一些有條件的處理,所以我試圖找到列表中的第一章:

<xsl:when test="count(preceding-sibling::*[($layout = 'one')]) = '0'"> 
    <xsl:call-template name="processChapterOne"/> 
</xsl:when> 

這是事情變得怪異的時候。我的測試永遠不會變爲真:列表中第一章的count(...)的值爲4,並從那裏增加。它看起來像是統計所有頂層元素,而不僅僅是名爲「章節」的元素。 當我將代碼更改爲:

<xsl:when test="count(preceding-sibling::*[(@template = 'one')]) = '0'"> 
    <xsl:call-template name="processChapterOne"/> 
</xsl:when> 

它可以正常工作。所以我用直接引用替換了一個變量。我無法弄清楚爲什麼這會有所作爲。什麼會造成這種情況?

回答

1

不工作工作案件實際上是非常不同的:

  1. 不工作:在preceding-sibling::*[$layout = 'one']$layout始終是one作爲它的值相同當時最初設置在<xsl:variable name="layout" select="@template"/>聲明中。

  2. 工作:在preceding-sibling::*[@template = 'one']@template每變化前同輩上下文節點的@template屬性值而變化。

+1

啊,我明白了。我假定'$ layout'會擴展到'@ template',但是當我聲明變量時'$ layout'被當前節點的'@ template'的值填充。 – Hobbes

+0

是的,這是正確的。 – kjhughes

0
*[(@template = 'one')] 

上面的意思是:統計所有nodes其中attribute template等於文本one

*[($layout = 'one')] 

上面的意思是:統計所有nodes其中變量layout等於文本one。 我覺得你提出的問題$layout沒有填充文字one,但它確實是xsl:call-template。也許這裏有什麼問題?

此外,如果你不想統計所有nodes但只有chapter節點。這樣做:

chapter[($layout = 'one')] 
chapter[(@template = 'one')]