Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT XML to XML Remove node if specific child not does not exist

Tags:

xml

xslt

I'm new to XSL, and not able to find information on this question. This is only for XSLT 1.0, and will eventually be run from XSLTproc.

Here is an example XML

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

Basically, I want to keep everything except :

  • remove any node with no <child>
  • remove all <step-child>

I can only figure out how to remove unwanted nodes, but even that is questionable. I really appreciate any help with this.

like image 515
J. M. Becker Avatar asked Jun 01 '12 21:06

J. M. Becker


1 Answers

<?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>
like image 179
Mads Hansen Avatar answered Oct 18 '22 20:10

Mads Hansen