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("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
xml=xmlOutput.getWriter().toString();
System.out.println("THE RESULT XML "+xml);
:) would be better if the example shows the result as well. :)
ReplyDeleteThanks for this XML tutorial. I'm afraid I'm better acquainted with offset printing than XML printing!
ReplyDeleteThe CR/LFs, if any, need to be removed first, else it won't work!
ReplyDeleteI 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.
ReplyDeletelong island document scanning