【发布时间】:2011-03-17 10:27:16
【问题描述】:
我目前正在用 java 将 xml 写入 xml doc,但它的格式不正确,它的格式如下:
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
我可以做些什么来将其与文档的其余部分正确对齐,而不是这样?
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
我收到了关于可能重复的回复,可能是这种情况,但在我的情况下,我的代码在这里不起作用:
private void writeFile(File file) {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult resultStream = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(getDocument());
transformer.transform(source, resultStream);
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(resultStream.getWriter().toString().trim());
out.close();
}
【问题讨论】:
-
可能重复是的,只是它不起作用,让我更新我的问题
-
你试过transformer.setOutputProperty("indenting", "4");和transformerFactory.setAttribute("缩进数", new Integer(2));我问是因为您的代码没有显示。
-
我还没有尝试过,我会在稍后回复你。tnx
-
@nhnb 第一个抛出这个异常:
Attempting to access invalid Transformer property 'indenting'第二个有编译错误