2010-04-02 67 views
0

我希望我能做的xsl如下,但不幸的父/位()是無效的。如何獲取父元素的位置 - XSL

XSL

<xsl:template match="li"> 
    <bullet> 
    <xsl:apply-templates/> 
    </bullet> 
    <!-- if this is the last bullet AND there are no more "p" tags, output footer --> 
    <xsl:if test="count(ancestor::div/*) = parent/position()"> 
    <footer/> 
    </xsl:if> 
</xsl:template> 

XML

<html> 
    <div> 
    <p>There is an x number of me</p> 
    <p>There is an x number of me</p> 
    <p>There is an x number of me</p> 
    <ul> 
     <li>list item</li> 
     <li>list item</li> 
     <li>list item</li> 
     <li>list item</li> 
     <li>list item</li> 
    </ul> 
    </div> 
</html> 

任何人有任何想法如何找出從這個問題內我的模板匹配裏?

謝謝!

+0

@joe:沒有任何相關的髒話,我再說一遍,這是不是在XSLT的精神。請用xml文檔顯示一個完整的(但最小的)例子,想要的結果以及應該如何從源xml文檔中獲得結果。然後很多人將能夠顯示出正確的解決方案,這可能不會比較職位。 – 2010-04-02 16:46:34

回答

1

試試這個:

<xsl:template match="li"> 
    <bullet> 
    <xsl:apply-templates/> 
    </bullet> 
    <xsl:if test="position()=last() and not(../following-sibling::p)"> 
    <footer/> 
    </xsl:if> 
</xsl:template> 
2

的一個好方法在XSLT做,這是

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 

<xsl:template match="node()|@*"> 
    <xsl:copy> 
    <xsl:apply-templates select="node()|@*"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="div"> 
    <xsl:apply-templates/> 
    <footer/> 
</xsl:template> 

<xsl:template match="li"> 
    <bullet> 
    <xsl:apply-templates/> 
    </bullet> 
</xsl:template> 
</xsl:stylesheet> 

<footer/>列入是最自然的匹配div,也沒有必要試圖將模板結束比較任何職位。

+0

你對我的問題的最後一行毫不知情。我需要從我的模板匹配中爲李做這個。這只是一個讓人更容易解釋的人爲的例子。 – joe 2010-04-02 16:28:09

+0

但我能夠重構我的代碼以您描述的方式工作。謝謝!有人說,我打算繼續解決這個問題,因爲在比賽外移動

並不容易,如果它是一個很大的xsl文件,在多個地方調用「li」上的apply-templates。 – joe 2010-04-02 16:44:00

+0

@joe:沒有任何咒罵,我再說一遍,這不符合XSLT的精神。請用xml文檔顯示一個完整的(但最小的)例子,想要的結果以及應該如何從源xml文檔中獲得結果。然後很多人將能夠顯示出正確的解決方案,這可能不會比較職位。 – 2010-04-02 16:45:35

0

如果我理解正確,您正在尋找最後的li;這是一個li,它後面沒有li個元素。這可以測試像這樣:

<xsl:template match="li"> 
    <bullet> 
    <xsl:apply-templates/> 
    </bullet> 
    <xsl:if test="not(following-sibling::li)"> 
    <footer /> 
    </xsl:if> 
</xsl:template> 

雖然在情況下,你已經給了它似乎更在XSLT的精神來添加腳註處理ul結束的時候:

<xsl:template match="ul"> 
    <ul> 
    <xsl:apply-templates/> 
    </ul> 
    <footer /> 
</xsl:template> 

<xsl:template match="li"> 
    <bullet> 
    <xsl:apply-templates/> 
    </bullet> 
</xsl:template> 
4

您可以通過計算它的前面的兄弟姐妹找到源代碼樹中的父節點的位置:

<xsl:variable name="parent-position" 
       select="count(../preceding-sibling::*) + 1"/> 

如果要確定是否有任何pul元素之後的元素,你可以不使用位置在所有的測試:

<xsl:if test="../following-sibling:p">...</xsl:test> 

然而,隨着Dimitre和奧利弗已經注意到,在處理父元素時,它更多的是XSLT的精神來添加腳註。另外,所顯示的XPath表達式只關心原始源樹中的順序。如果打算過濾元素或在處理前用xsl:sort重新排序,這些路徑將無法按預期工作,因爲它們將查看原始排序幷包括源樹中的所有節點。