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>
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With