2011-03-17 13 views
2
<a> 
    <x/> 
    <m/> 
    <y/> 
    <m/> 
</a> 

內部匹配「A」,我想匹配(第一)任何「米的前‘Y’的模板,然後 分別'y'後的任何'm'。有些模糊有關XPath「以下」軸(如在XSLT使用)

<xsl:apply-templates select="./m[following::y]"/> 

是我想的,但我不能得到它的工作,並進一步,我看不出如何防止這種正常的流動施加的「M」匹配的模板以及我想插入m相關內容的特定位置。

回答

3

您的模板看起來不錯,但是您確定要使用following?例如,這個模板:

<xsl:template match="a"> 
    <a><xsl:apply-templates select="m[following::y]"/></a> 
    <b><xsl:apply-templates select="m[following-sibling::y]"/></b> 
</xsl:template> 

...應用於以下XML:

<a> 
    <x/> 
    <m>match</m> 
    <y/> 
    <m>no match</m> 
    <nested> 
     <m>match 2</m> 
     <y/> 
    </nested> 
</a> 

...輸出以下結果:

<a>matchno match</a> 
<b>match</b> 

第一apply-templates比賽<m>no match</m>,因爲following包括文檔順序中上下文節點之後的所有節點,其中包括嵌套的<y/>

第二個模板僅匹配兄弟。

爲了完整起見,我將添加下面的模板,只匹配那些<m>節點,其立即下面的兄弟是<y>

<xsl:template match="a"> 
    <a><xsl:apply-templates select="m[following-sibling::*[1][self::y]]"/></a> 
</xsl:template> 

此模板的以下輸出給出了上述XML:

<a>match</a> 
+0

+1對於「跟隨」和「跟隨兄弟姐妹」的差異。 – 2011-03-17 16:22:27