IMPORTANT:
this is not a Support Forum! Experienced users might answer from time to time questions posted here. If you need a professional and reliable answer, or if you want to report a bug, please contact Altova Support instead.

Stripping only empty elements without attributes Options · View
cycotron69
Posted: Friday, October 30, 2009 7:35:55 PM
Rank: Member

Joined: 1/19/2005
Posts: 6
Location: US
I've been using the following script to remove any elements without a value or contains only white-space from our XMLs.

Code:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
    <xsl:preserve-space elements="*"/>
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*[not(normalize-space())]"/>
</xsl:stylesheet>


This script will even remove empty elements with attributes. I however would like to keep those. So for example running the script on the following XML:

Code:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Parent1>
        <Child1 abc="xyz" >Me</Child1>
    </Parent1>
    
    <Parent2/>
    
    <Parent3>
        <Child3 abc="xyz"/>
    </Parent3>
    
    <Parent4>
        <Child4>  </Child4>
    </Parent4>
</Root>


Results in:
Code:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Parent1>
        <Child1 abc="xyz">Me</Child1>
    </Parent1>
</Root>


But what I want is:
Code:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Parent1>
        <Child1 abc="xyz" >Me</Child1>
    </Parent1>

    <Parent3>
        <Child3 abc="xyz"/>
    </Parent3>
</Root>


I tried a couple of different modifications to the original script with no luck. Any help would be great. Many thanks in advance.
vlad
Posted: Friday, October 30, 2009 8:39:17 PM
Rank: Advanced Member

Joined: 12/13/2005
Posts: 2,856
Location: Mauritius
Try this

<xsl:template match="*[not(normalize-space()) and not(.//@*)]"/>
Users browsing this topic
guest

Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Use of the Altova User Forum(s) is governed by the Altova Terms of Use.