How to pretty print XML from Java?
To pretty print XML from Java, you can use the javax.xml.transform.Transformer
class from the Java XML Transformer API.
Here's an example of how you can use this class to pretty print an XML document:
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
public class XmlUtils {
public static void prettyPrint(Document xml) throws TransformerException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(xml);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
}
}
This code defines a prettyPrint
method that takes an org.w3c.dom.Document
object as an argument and pretty prints it to the console using the Transformer
class.
To use this method, you can simply call it and pass in your XML document:
Document xml = ...; // parse the XML document
XmlUtils.prettyPrint(xml);
This will pretty print the XML document to the console. You can also modify the StreamResult
object to write the pretty-printed XML to a file or other output stream.