gpt4 book ai didi

java - 使用 Transformer 格式化输出 XML

转载 作者:行者123 更新时间:2023-12-01 04:40:52 27 4
gpt4 key购买 nike

是否可以格式化 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);

最佳答案

我会将 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" />

关于java - 使用 Transformer 格式化输出 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16577746/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com