Home > Back-end >  xslt remove item if subnode doesn't exist
xslt remove item if subnode doesn't exist

Time:09-15

I have the following input xml.

<response>
<customers>
    <customer>
        <id>001</id>
        <addresses>
            <address>
                <id>a01</id>
                <street/>
            </address>
            <address>
                <id>a02</id>
                <street/>
            </address>
        </addresses>
    </customer>
    <customer>
        <id>002</id>
        <addresses/>
    </customer>
</customers>

If the subelement addresses doesn't exist or if it's empty (like this ) I need to remove the father element customer.

<response>
<customers>
    <customer>
        <id>001</id>
        <addresses>
            <address>
                <id>a01</id>
                <street/>
            </address>
            <address>
                <id>a02</id>
                <street/>
            </address>
        </addresses>
    </customer>
</customers>

This is the xslt v 1.0 I use but it doesn't work

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="customer[not(descendant::address[not(*)][normalize-space()])]"/>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>

Can you help me?

CodePudding user response:

If you want to exclude the customer elements that do not have a address descendant:

<xsl:template match="customer[not(descendant::address)]"/>

If you want to exclude the customer elements that do not have an address descendant with some text() value descendants:

<xsl:template match="customer[not(descendant::address[normalize-space()])]"/>
  • Related