2012-03-26 107 views
3

我需要從元素中刪除值,但將元素本身作爲空元素保留在輸出XML中。XSLT刪除元素的值

我的輸入文件:

<a> 
    <b>TEXT1 
     <c>123</c> 
     <d>qwe</d> 
     <e>rty</e> 
    </b> 
    <b>TEXT2 
    <c>345</c> 
    <d>iop</d> 
    <e>jkl</e> 
    </b> 
</a> 

輸出文件應保留C元素,但元素中的數字應該是沒有了。

<a> 
<b>TEXT1 
    <c></c> 
    <d>qwe</d> 
    <e>rty</e> 
</b> 
<b>TEXT2 
    <c></c> 
    <d>iop</d> 
    <e>jkl</e> 
</b> 
</a> 

回答

0

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output indent="yes"/> 
    <xsl:strip-space elements="*"/> 

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

    <xsl:template match="c"> 
    <c/> 
    </xsl:template> 

</xsl:stylesheet> 

XML輸出

<a> 
    <b>TEXT1 
    <c/> 
     <d>qwe</d> 
     <e>rty</e> 
    </b> 
    <b>TEXT2 
    <c/> 
     <d>iop</d> 
     <e>jkl</e> 
    </b> 
</a> 

注:<c/><c></c>是等價的。

3

更簡單/短

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

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

<xsl:template match="c/text()"/> 
</xsl:stylesheet> 
+0

,當然還有 「| @ *」 是多餘的,如果源文件不包含任何屬性。 – 2012-03-27 07:18:46

+2

@邁克凱:是的。保持這種冗餘可以使相同的代碼不僅能夠正確處理具體提供的文檔,還能正確處理一類文檔,其中一些文檔具有屬性。 – 2012-03-27 12:34:22