首页 > 解决方案 > xsl如何使用xsl删除父级下的大量xml元素

问题描述

我有一个如下的 xml 结构:

<Parent>
<child1></child1>
<child2></child2>
<child3></child3>
...
...
</Parent>

假设有大约 20 个子 xml 元素需要删除,并且元素下只保留 3 个 xml 元素<Parent>

我知道使用身份模板,例如下面的模板可以删除 xml 文件中的一个元素。

<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="child1"/>

但事情是我必须删除 20 个 xml 子元素并且只保留其中的 3 个。如何使代码尽可能少地实现这一点?

标签: xslt

解决方案


自己想出来的。我做了以下事情:

<xsl:template match="Parent">
<xsl:copy>
     <xsl:apply-templates select="child1"/>
     <xsl:apply-templates select="child2"/>
     <xsl:apply-templates select="child3"/>
  </xsl:copy>

</xsl:template>

并将模板应用到的父节点上<Patent>

<xsl:copy>
     <xsl:apply-templates/>
  </xsl:copy>

推荐阅读