XSLT XML to XML如果不存在特定子项,则删除节点

时间:2012-06-01 21:32:46

标签: xml xslt

我是XSL的新手,无法找到有关此问题的信息。这仅适用于XSLT 1.0,最终将从XSLTproc运行。

这是一个示例XML

<root>
    <node>
        <data />
        <child>
            <grandchild />
        </child>
        <step-child action="removenode" />
    </node>
    <node>
        <data />
        <step-child action="removenode" />
    </node>
</root>

基本上,我想保留除了以外的所有内容:

  • 删除没有<child>
  • 的任何节点
  • 删除所有<step-child>

我只能弄清楚如何删除不需要的节点,但即便如此也是有问题的。我真的很感激任何帮助。

1 个答案:

答案 0 :(得分:10)

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <!--Identity template to copy all content by default-->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--Remove node elements that do not have child elements, 
               and remove step-child elements -->
    <xsl:template match="node[not(child)] | step-child"/>

</xsl:stylesheet>