创建XML只打印到一行 [英] Creating XML only printing to one line
本文介绍了创建XML只打印到一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个将地图写入XML的代码。它似乎工作,但文件打印没有新的行。所以在任何XML编辑器中,它只在一行。如何将它打印到每个孩子的新行?
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);
推荐答案
我使用
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");
哪个似乎很正常。
这篇关于创建XML只打印到一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文