代码之家  ›  专栏  ›  技术社区  ›  crauscher

使用XSLT转换删除xmlnodes

  •  0
  • crauscher  · 技术社区  · 15 年前

    我需要从XML文档中提取一些XML节点。来源是

    <root>
        <customElement>
            <child1></child1>
            <child2></child2>
        </customElement>
        <child3></child3>
        <child4></child4>
    </root>
    

    结果应该是

    <root>
        <child1></child1>
        <child2></child2>
        <child3></child3>
        <child4></child4>
    </root>
    

    如您所见,只删除了“customElement”元素,但子元素仍然是结果文档的一部分。 如何使用XSLT转换来实现这一点。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Jon W    15 年前

    下面是一个简单的解决方案:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" omit-xml-declaration="no"/>
    
    <!-- identity template -->
    <xsl:template match="@*|node()">
        <xsl:copy>
           <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    <!-- here we specify behavior for the node to be removed -->
    <xsl:template match="customElement">
       <xsl:apply-templates select="@*|node()"/>
    </xsl:template>
    
    </xsl:stylesheet>