Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Remove empty XML tags

Tags:

java

xml

tags

I'm looking for a simple Java snippet to remove empty tags from a (any) XML structure

<xml>
    <field1>bla</field1>
    <field2></field2>
    <field3/>
    <structure1>
       <field4>bla</field4>
       <field5></field5>
    </structure1>
</xml>

should turn into;

<xml>
    <field1>bla</field1>
    <structure1>
       <field4>bla</field4>
    </structure1>
</xml>
like image 520
Raymond Avatar asked Nov 06 '09 12:11

Raymond


1 Answers

This XSLT stylesheet should do what you're looking for:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="@*|node()">
    <xsl:if test=". != '' or ./@* != ''">
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

It should also preserve elements which are empty but have attributes which aren't. If you don't want this behaviour then change:

<xsl:if test=". != '' or ./@* != ''">

To: <xsl:if test=". != ''">

If you want to know how to apply XSLT in Java, there should be plenty of tutorials out there on the Interwebs. Good luck!

like image 100
Chris R Avatar answered Nov 09 '22 23:11

Chris R