如何使用 XSLT 从 XML 文件中删除不需要的元素和属性 [英] How to remove unwanted elements and attributes from XML file using XSLT

查看:36
本文介绍了如何使用 XSLT 从 XML 文件中删除不需要的元素和属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 XML 文件,我想照原样复制它,但我想过滤一些不需要的元素和属性,例如以下是原始文件:

I have XML file , I want to copy it as it is , but I want to filter some unwanted elements and attributes , for example the following is the original file :

<root>
<e1 att="test1" att2="test2"> Value</e1>
<e2 att="test1" att2="test2"> Value 2 <inner class='i'>inner</inner></e2>
<e3 att="test1" att2="test2"> Value 3</e3>

</root>

过滤后(e3 元素和 att2 属性已被删除):

After the filtration ( e3 element and att2 attribute have been removed ) :

<root>
<e1 att="test1" > Value</e1>
<e2 att="test1" > Value 2 <inner class='i'>inner</inner></e2>
</root>

注意事项:

  • 如果可能的话,我更喜欢使用 ( for-each 元素而不是 apply-templates )
  • 我在使用 xsl:elementxsl:attribute 时遇到一些问题,因为我无法写入当前节点名称
  • I prefer to use ( for-each element instead of apply-templates if that possible )
  • I have some problems with xsl:element and xsl:attribute since I could not write the current node name

谢谢

推荐答案

我知道你更喜欢使用 for-each,但为什么不使用身份转换,然后用什么覆盖该模板你不想保留?

I know you'd prefer to use for-each, but why not use an identity transform and then override that template with what you don't want to keep?

这个样式表:

<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="e3|@att2"/>

</xsl:stylesheet>

产生:

<root>
   <e1 att="test1"> Value</e1>
   <e2 att="test1"> Value 2 <inner class="i">inner</inner>
   </e2>
</root>

这篇关于如何使用 XSLT 从 XML 文件中删除不需要的元素和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆