user2631055
user2631055

Reputation: 27

Removing empty XML node using XSLT

I am looking for a help I am writting a XSL to remove empty nodes, it is working but If I have xsi:xsi = true in one of the XML node, then it is not removing that node, I need style sheet which remove empty node, empty attributes and node which contain xsi:xsi = true

INPUT XML

<root>
<para>
 <Description>This is my test description</Description>
 <Test></Test>
 <Test1 attribute="1"/>
 <Received_Date xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
</para>
</root>

OutPut XML

<root>
<para>
 <Description>This is my test description</Description> 
 <Test1 attribute="1"/>
 <Received_Date xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
</para>

Expected Output

<root>
<para>
 <Description>This is my test description</Description> 
 <Test1 attribute="1"/>
</para>
</root>

XSL Code

<?xml version="1.0" ?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output omit-xml-declaration="yes" indent="yes" />
    <xsl:template match="node()|SDLT">
        <xsl:if test="count(descendant::text()[string-length(normalize-space(.))>0]|@*)">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()" />
            </xsl:copy>
        </xsl:if>

    </xsl:template>
    <xsl:template match="@*">
        <xsl:copy />
    </xsl:template>
    <xsl:template match="text()">
        <xsl:value-of select="normalize-space(.)" />
    </xsl:template>

</xsl:stylesheet>

Upvotes: 1

Views: 549

Answers (1)

Rupesh_Kr
Rupesh_Kr

Reputation: 3445

You can use this:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    version="1.0">
    <xsl:output omit-xml-declaration="yes" indent="yes" />
    <xsl:template match="node()|SDLT">
        <xsl:if test="(node() or @* ) and not(@xsi:nil = 'true')">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()" />
            </xsl:copy>
        </xsl:if>

    </xsl:template>

    <xsl:template match="@*">
        <xsl:copy />
    </xsl:template>

    <xsl:template match="text()">
        <xsl:value-of select="normalize-space(.)" />
    </xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions