What is the shortest way to pretty print a org.w3c.dom.Document to stdout?

前端 未结 6 1392
难免孤独
难免孤独 2020-11-27 11:08

What is the easiest way to pretty print (a.k.a. formatted) a org.w3c.dom.Document to stdout?

6条回答
  •  Happy的楠姐
    2020-11-27 11:36

    This will return a nicely formated output by using recursive descent/ascent.

    private static boolean skipNL;
    private static String printXML(Node rootNode) {
        String tab = "";
        skipNL = false;
        return(printXML(rootNode, tab));
    }
    private static String printXML(Node rootNode, String tab) {
        String print = "";
        if(rootNode.getNodeType()==Node.ELEMENT_NODE) {
            print += "\n"+tab+"<"+rootNode.getNodeName()+">";
        }
        NodeList nl = rootNode.getChildNodes();
        if(nl.getLength()>0) {
            for (int i = 0; i < nl.getLength(); i++) {
                print += printXML(nl.item(i), tab+"  ");    // \t
            }
        } else {
            if(rootNode.getNodeValue()!=null) {
                print = rootNode.getNodeValue();
            }
            skipNL = true;
        }
        if(rootNode.getNodeType()==Node.ELEMENT_NODE) {
            if(!skipNL) {
                print += "\n"+tab;
            }
            skipNL = false;
            print += "";
        }
        return(print);
    }
    

提交回复
热议问题