algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

XML pretty-printing in Java

Suppose there is a String with XML file content in it
String xmlStr= "<error><error-id>1</error-id><error-name>ERR-ONE</error-one></error>";

When the xmlStr is printed using Java streams, it prints in a single line sans formatting and indentation.

To get it ‘pretty-printed’, javax XML API library can be used.

Source xmlInput = new StreamSource(new StringReader(xml)); 
StreamResult xmlOutput = new StreamResult(new StringWriter());
Transformer transformer = TransformerFactory.newInstance().newTransformer();
//transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
System.out.println("THE RESULT XML "+xml);


  1. :) would be better if the example shows the result as well. :)

  2. Thanks for this XML tutorial. I'm afraid I'm better acquainted with offset printing than XML printing!

  3. The CR/LFs, if any, need to be removed first, else it won't work!

  4. I agree with JawaharI that it would be better if you can show us visual aid of the result of these codes. I will try this pretty-printing later.

    long island document scanning

  5. Moreover, after completion, the whole products get delivered at your doorstep without any additional charges.

  6. From the exceptionally unsurprising blurb and flag, yields proceed onward to brilliant display design easily. Different alternatives are names, POS materials, window representation, signs, bundling evidences, and floor illustrations other than additional.


Search 24 Bytes