Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

dom

xml

w3c

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

like image 326
flybywire Avatar asked Feb 24 '10 10:02

flybywire


2 Answers

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)

like image 183
Bozho Avatar answered Oct 18 '22 11:10

Bozho


How about:

OutputFormat format = new OutputFormat(doc); format.setIndenting(true); XMLSerializer serializer = new XMLSerializer(System.out, format); serializer.serialize(doc); 
like image 25
Dennis Avatar answered Oct 18 '22 11:10

Dennis