使用XSLT删除元素的值

3
我需要从一个元素中移除一个值,但是在输出的XML中保留这个元素为空元素。
我的输入文件:
<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>
2个回答

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>

当然,如果源文档不包含属性,则“|@*”是多余的。 - Michael Kay
2
@MichaelKay:是的。保持这种冗余性允许相同的代码正确处理不仅特定提供的文档,还有一类文档,其中一些将具有属性。 - Dimitre Novatchev

1

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> 是等价的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接