我创建了一些将映射写入 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);