2012-03-26 151 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