PDA

View Full Version : remove null elements


anantarora
10-07-2005, 10:47 AM
Hi,

I want to write an xslt wherein I take an input xml and remove all the null elements from it in the output xml and their parent elements if they are empty too.

Note: Elements having non-empty attributes are not empty and hence, should be reflected in the output.

Example: Input

<?xml version="1.0" encoding="UTF-8"?>
<Orders>
<Order>
<name>
<firstname>anant</firstname>
<lastname></lastname>
</name>

<address>
<firstline>
<sub1></sub1>
<sub2></sub2>
</firstline>
<secondline>
<sub1 index="1"></sub1>
<sub2/>
</secondline>
</address>
</Order>
</Orders>

Output XML

<?xml version="1.0" encoding="UTF-8"?>
<Orders>
<Order>
<name>
<firstname>anant</firstname>
</name>

<address>
<secondline>
<sub1 index="1"></sub1>
</secondline>
</address>
</Order>
</Orders>

Alex Vincent
10-08-2005, 05:15 PM
Hm, this is interesting, and may not be directly doable with XSLT. You're removing not only elements with no child nodes and no attributes (set A), but also elements which have only elements from set A (set B), elements which have only elements from sets A and B (set C), etc. etc. etc.

For something like this, you may be much better off using a Document Object Model algorithm.

anantarora
10-10-2005, 05:02 AM
thanks for the reply. Nvr worked with DOM, could you give me the solution or atleast some references for the same.

I'll be highly grateful.thanks

KC-Luck
10-10-2005, 06:49 AM
try this:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml"/>

<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>

<xsl:template match="node()">
<xsl:variable name="hasText" select="string-length(normalize-space(.)) > 0"/>
<xsl:variable name="hasAttributes" select="count(.//*[count(@*) > 0]) > 0 or count(@*) > 0"/>
<xsl:choose>
<xsl:when test="local-name()">
<xsl:if test="$hasText or $hasAttributes">
<xsl:element name="{local-name()}">
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:element>
</xsl:if>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="."/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>

<xsl:template match="processing-instruction()"/>

</xsl:stylesheet>
enjoy!