Create only one-line XML printing

I created some code that writes the map in XML. It seems to work, but the file prints without new lines. Therefore, in any XML editor, it is only on one line. How can I print it for a new line for each child?

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); Element vdata = doc.createElement("vouchdata"); doc.appendChild(vdata); for (Entry<String, String> entry : vouchMap.entrySet()) { Element udata = doc.createElement("vouch"); Attr vouchee = doc.createAttribute("name"); vouchee.setValue(entry.getKey()); udata.setAttributeNode(vouchee); Attr voucher = doc.createAttribute("vouchedBy"); voucher.setValue(entry.getValue()); udata.setAttributeNode(voucher); vdata.appendChild(udata); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("vouchdata.xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); 
+8
java dom xml
source share
2 answers

I use

 Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.setOutputProperty(OutputKeys.METHOD, "xml"); tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); 

Everything seems to be working fine.

+19
source share

If this is the formatting of the generated xml, then consider the answer for

Java: writing DOM to XML file (formatting problems)

-one
source share

All Articles