加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何使用XSLT从XML文件中删除不需要的元素和属性

发布时间:2020-12-16 23:21:33 所属栏目:百科 来源:网络整理
导读:我有 XML文件,我想按原样复制它,但我想过滤一些不需要的元素和属性,例如以下是原始文件: roote1 att="test1" att2="test2" Value/e1e2 att="test1" att2="test2" Value 2 inner class='i'inner/inner/e2e3 att="test1" att2="test2" Value 3/e3/root 过滤后
我有 XML文件,我想按原样复制它,但我想过滤一些不需要的元素和属性,例如以下是原始文件:

<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属性已被删除):

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

笔记:

>我更喜欢使用(for-each元素而不是apply-templates,如果可能的话)
>我有xsl:element和xsl:属性的一些问题,因为我无法编写当前节点名称

谢谢

解决方法

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

这个样式表:

<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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读