Shravan Vishwanathan
Shravan Vishwanathan

Reputation: 113

Remove child node from parent node based on condition in XML

I am trying to remove the child nodes within the parent node based on a condition. But only the value is removed and not the element tags. I require to remove the element tags also.

XML:

 <?xml version="1.0" encoding="UTF-8"?>
    <DM CT="REJECT" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <atict:info tracking="on"      xmlns:atict="http://www.arbortext.com/namespace/atict"/>
    <atict:add user=""><SPECPARA>
    <WARNING VITAL="1">
    <PARA>abcdefghijk</PARA>
    </WARNING>
    </SPECPARA></atict:add>
    </DM>

Current output:

<?xml version="1.0" encoding="UTF-8"?>
    <DM CT="REJECT" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <atict:add user=""><SPECPARA>
    <WARNING VITAL="1">
    <PARA></PARA>
    </WARNING>
    </SPECPARA></atict:add>
    </DM>

Desired Output:

  <?xml version="1.0" encoding="UTF-8"?>
        <DM CT="REJECT" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

        </DM>

XSLT 1.0:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" extension-element-prefixes="img" exclude-result-prefixes="atict">
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="atict:add//text()[ancestor::DM/@CT='REJECT']"/>
</xsl:stylesheet>

How do I remove all the child nodes based on the condition?

Thanks for the support.

Upvotes: 0

Views: 946

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116959

I am guessing you want to do:

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="DM[@CT='REJECT']">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions