Java Remove empty XML tags

前端 未结 9 2390
死守一世寂寞
死守一世寂寞 2020-12-11 16:57

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


    bla
    <         


        
9条回答
  •  没有蜡笔的小新
    2020-12-11 17:56

    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);
        }
    }
    

提交回复
热议问题