I have a XML document in a String and would like to prettyPrint (newlines after tags and indentation) it to a file, so far the solution at https://stackoverflow.com/a/25865324/3229995 is working for me almost as I want.
The problem is, it is using System.out, and I would like to write the output to a file, ensuring that the UTF-8 encoding is kept.
Below is how I modified the code. It runs and outputs an XML file on a test XML string as shown in https://stackoverflow.com/a/25865324/3229995.
My questions are:
Do I need to flush or close the writer or out? If so, at what part of the code?
I am worried that without flushing or closing, there could be cases where not the whole XML will be output.
public static void main(String[] args){
String xmlString = "<hello><from>ME</from></hello>";
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new InputSource(new StringReader(xmlString)));
// NEW: using FileOutputStream and Writer
OutputStream out = new FileOutputStream("/path/to/output.xml");
Writer writer = new OutputStreamWriter(out, "UTF-8");
pretty(document, writer, 2);
}
private static void pretty(Document document, Writer writer, int indent) throws Exception {
document.setXmlStandalone(true);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
if (indent > 0) {
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent));
}
// NEW: passing the writer
Result result = new StreamResult(writer);
Source source = new DOMSource(document);
transformer.transform(source, result);
}