xmlxsltelementremovechild

Remove xml element if subelements are empty or don't exist


I need to remove an xml element if both the subelements fiel1 and field2 don't exist or are blank. Input and expected result (see comments)

<root><!-- document -->
  <element><!-- keep -->
    <field1>A</field1>
  </element>
  <element><!-- keep -->
    <field2>B</field2>
  </element>
  <element><!-- delete -->
    <field1/>
  </element>
  <element><!-- delete></element>
  <element/><!-- delete -->
</root>

non-working Xsl (v.1 required)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
    <xsl:copy-of select="node()"/>
</xsl:template>
<xsl:template match="element">
    <xsl:choose>
        <xsl:when test="field1 or field2">
            <xsl:copy>
                <xsl:copy-of select="node()"/>
            </xsl:copy>
        </xsl:when>
        <xsl:otherwise/>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>

Could anybody help please? Thanks


Solution

  • A common approach to problems like this is to copy everything as is as the rule, with an empty template making an exception for the nodes you want to delete:

    XSLT 1.0

    <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"/>
    <xsl:strip-space elements="*"/>
    
    <!-- identity transform -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="element[not(field1/text() or field2/text())]"/>
    
    </xsl:stylesheet>
    

    In a simple case such as your example you could reduce this to:

    <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"/>
    <xsl:strip-space elements="*"/>
    
    <xsl:template match="/root">
        <xsl:copy>
            <xsl:copy-of select="element[field1/text() or field2/text()]"/>
        </xsl:copy>
    </xsl:template>
    
    </xsl:stylesheet>