是否可以从Transformer对象格式化输出XML文件。
截至目前,我将这些作为输出:
<A name="a" type="a">
<B name="b" type="b" width="100" height="100" />
<B name="b" type="b" width="100" height="200" />
<B name="b" type="b" width="100" height="300" />
<B name="b" type="b" width="100" height="400" />
</A>
但我想要的东西看起来像这样:
<A name="a"
type="a">
<B name="b"
type="b"
width="100"
height="100" />
<B name="b"
type="b"
width="100"
height="200" />
<B name="b"
type="b"
width="100"
height="300" />
<B name="b"
type="b"
width="100"
height="400" />
</A>
以下是变压器的代码片段:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
答案 0 :(得分:0)
我会将xml保存在tmp文件中,然后逐行读取并保存。一行示例
String line = " <B name=\"b\" type=\"b\" width=\"100\" height=\"100\" />";
String indent = line.startsWith("<A") ? " " : " ";
line = line.replaceAll("(type|width|height)", "\n" + indent + "$1");
System.out.println(line);
输出
<B name="b"
type="b"
width="100"
height="100" />