简体   繁体   中英

Creating XML only printing to one line

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM