I am using the following code to indent an xml document which is provided to me as a string.
I am using the JDK implementation of org.w3c.dom.ls
, if that matters.
http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/ls/package-summary.html
public String format(String xml) {
try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));
//May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified.
writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.
return writer.writeToString(document);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Is there a way to define any of the following:
- size of indentation
- whether to do text wrapping or not,
- maximum line length if I want to do text wrapping
I've tried looking at the javadocs, and online examples... but could not find any example. I only saw examples that use an old API, which is now deprecated.