Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I was wondering whether it would be easy to do this with the <a href="http://www.xom.nu/" rel="nofollow noreferrer">XOM</a> library and gave it a try. </p> <p>It turned out to be quite easy:</p> <pre><code>import nu.xom.*; import java.io.File; import java.io.IOException; public class RemoveEmptyTags { public static void main(String[] args) throws IOException, ParsingException { Document document = new Builder().build(new File("original.xml")); handleNode(document.getRootElement()); System.out.println(document.toXML()); // empty elements now removed } private static void handleNode(Node node) { if (node.getChildCount() == 0 &amp;&amp; "".equals(node.getValue())) { node.getParent().removeChild(node); return; } // recurse the children for (int i = 0; i &lt; node.getChildCount(); i++) { handleNode(node.getChild(i)); } } } </code></pre> <p>This probably won't handle all corner cases properly, like a completely empty document. And what to do about elements that are otherwise empty but have attributes?</p> <p>If you want to save XML tags with attributes, we can add in the method 'handleNode' the following check:</p> <pre><code>... &amp;&amp; ((Element) node).getAttributeCount() == 0) ) </code></pre> <p>Also, if the xml has two or more empty tags, one after another; this recursive method doesn't remove all empty tags!</p> <p>(This answer is part of my evaluation of XOM as a potential <a href="https://stackoverflow.com/questions/831865/what-java-xml-library-do-you-recommend-to-replace-dom4j">replacement to dom4j</a>.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload