I\'m looking for a simple Java snippet to remove empty tags from a (any) XML structure
bla
<
To remove all empty tags, even if they are one after another, one possibile solution is:
private void removeEmptyTags(Document document) {
List listNode = new ArrayList();
findListEmptyTags(document.getRootElement(), listNode);
if (listNode.size() == 0)
return;
for (Node node : listNode) {
node.getParent().removeChild(node);
}
removeEmptyTags(document);
}
private void findListEmptyTags(Node node, List listNode) {
if (node != null && node.getChildCount() == 0 && "".equals(node.getValue()) && ((Element) node).getAttributeCount() == 0) {
listNode.add(node);
return;
}
// recurse the children
for (int i = 0; i < node.getChildCount(); i++) {
findListEmptyTags(node.getChild(i), listNode);
}
}