2017-04-11 128 views
0

我要刪除元素d和評論<!-- d -->當家長有屬性c="string1"XSLT:刪除一個孩子時,父母有一個屬性

輸入:

<a> 
<b c="string1"> 
    <!-- d --> 
    <d> 
    <e/> 
    </d> 
    <f/> 
</b> 

<b c="string2"> 
    <!-- d --> 
    <d> 
    <e/> 
    </d> 
    <f/> 
</b> 
</a> 

所需的輸出:

<a> 
<b c="string1"> 
    <f/> 
</b> 

<b c="string2"> 
    <!-- d --> 
    <d> 
    <e/> 
    </d> 
    <f/> 
</b> 
</a> 

XSLT:

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

    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/> 

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

    <!-- Those templates do not work --> 
    <xsl:template match="d[???]" /> 
    <xsl:template match="comment()="d" /> 
</xsl:stylesheet> 

回答

1

這裏你可以看看它的一種方法:

<xsl:template match="b[@c='string1']/d" /> 
<xsl:template match="b[@c='string1']/comment()[.=' d ']" /> 

或者,如果你喜歡:

<xsl:template match="b[@c='string1']"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()[not(self::d or self::comment()[.=' d '])]"/> 
    </xsl:copy> 
</xsl:template> 

注意,在給定的例子註釋的值實際上是" d "即由空格包圍的字符"d"

0

找到了解決方案。這兩個xsl:模板可以工作。

<xsl:template match="d[ancestor::b[@c='string1']]" /> 
<xsl:template match="comment()[contains(.,'d') and ancestor::b[@c='string1']]" /> 

我寧願不使用contains(.,'d')但對註釋的文本的平等表達,但我不知道怎麼寫的表達。

+0

你想要的平等表達式是'。 ='d''。不要忽視'd'兩邊的空間。 –

+0

此外,使用普通路徑表達式代替祖先軸上的謂詞表達式測試節點更爲傳統。例如,'match =「b [@ c ='string1']/d」'。 –

相關問題