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

前端之家收集整理的这篇文章主要介绍了如何使用XSLT从XML文件中删除不需要的元素和属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_502_4@
我有 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:属性的一些问题,因为我无法编写当前节点名称

谢谢

@H_502_4@

解决方法

我知道你更喜欢使用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>
@H_502_4@ @H_502_4@

猜你在找的XML相关文章