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

前端 未结 6 1386
难免孤独
难免孤独 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条回答
  •  离开以前
    2020-11-27 11:58

    Call printDocument(doc, System.out), where that method looks like this:

    public static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    
        transformer.transform(new DOMSource(doc), 
             new StreamResult(new OutputStreamWriter(out, "UTF-8")));
    }
    

    (The indent-amount is optional, and might not work with your particular configuration)

提交回复
热议问题