8

I created some code that writes a map to XML. It appears to be working but the file is printed with no new lines. So in any XML editor its only on one line. How can I have it print to 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);
darcyy
  • 5,236
  • 5
  • 28
  • 41
meriley
  • 1,831
  • 3
  • 20
  • 33
  • 3
    See http://stackoverflow.com/questions/1264849/pretty-printing-output-from-javax-xml-transform-transformer-with-only-standard-j – Thorn G Dec 18 '12 at 02:55

2 Answers2

22

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");

Which seems to work just fine.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • @Tony This little hack to me weeks for Googling and trial and error. Glad I saved you the hasel ;) – MadProgrammer Dec 16 '13 at 01:59
  • Perfect: it helped me so much after half a day trying to find out what is wrong with my XML output (long one line only) - this solved it, upvoted! – qraqatit Jan 20 '20 at 20:38
-1

If it is formatting of generated xml then consider the answer for

Java: Writing a DOM to an XML file (formatting issues)

Community
  • 1
  • 1
abson
  • 9,148
  • 17
  • 50
  • 69