What is the shortest way to pretty print a org.w3c.dom.Document to stdout?
private void printNode(Node rootNode, String spacer) {
System.out.println(spacer + rootNode.getNodeName() + " -> " + rootNode.getNodeValue());
NodeList nl = rootNode.getChildNodes();
for (int i = 0; i < nl.getLength(); i++)
printNode(nl.item(i), spacer + " ");
}
Try jcabi-xml with one liner:
String xml = new XMLDocument(document).toString();
This is the dependency you need:
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-xml</artifactId>
<version>0.14</version>
</dependency>
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)
How about:
OutputFormat format = new OutputFormat(doc);
format.setIndenting(true);
XMLSerializer serializer = new XMLSerializer(System.out, format);
serializer.serialize(doc);