java 创建仅打印到一行的 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13925608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating XML only printing to one line
提问by meriley
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?
我创建了一些将映射写入 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);
回答by MadProgrammer
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.
这似乎工作得很好。
回答by abson
If it is formatting of generated xml then consider the answer for
如果它是生成的 xml 的格式,那么请考虑以下答案