仅创建XML打印到一行

时间:2012-12-18 02:54:37

标签: java xml dom

我创建了一些将地图写入XML的代码。它似乎工作但文件打印没有新行。所以在任何XML编辑器中它只在一行上。如何为每个孩子打印到新行?

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

2 个答案:

答案 0 :(得分:19)

我用

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

这似乎工作正常。

答案 1 :(得分:-1)

如果是格式化生成的xml,请考虑

的答案

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