我正在使用以下代码编写一个 XML 文件:
Source source = new DOMSource(rootElement);
Result result = new StreamResult(xmlFile);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
这是输出文件:
<?xml version="1.0" encoding="UTF-8"?>
<feature-sequences>
<sequence>
<initial-frame>0</initial-frame>
<points>
<point>
<x>274.0</x>
<y>316.0</y>
</point>
...
我希望这个文件缩进,例如:
<?xml version="1.0" encoding="UTF-8"?>
<feature-sequences>
<sequence>
<initial-frame>0</initial-frame>
<points>
<point>
<x>274.0</x>
<y>316.0</y>
</point>
...
在我的代码中调用 setOutputProperty
并没有解决问题,它实际上使文本换行(但不缩进)。
谁有解决这个问题的方法,而不需要外部库?
最佳答案
您可能还需要指定缩进的空格数:
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
关于java - 使用 Transformer 缩进 XML 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1082886/