使用Transformer缩进XML文本

cd1*_*cd1 1 java xml formatting indentation

我正在编写一个包含以下代码的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);
Run Code Online (Sandbox Code Playgroud)

这是输出文件:

<?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>
...
Run Code Online (Sandbox Code Playgroud)

我希望这个文件缩进,例如:

<?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>
...
Run Code Online (Sandbox Code Playgroud)

setOutputProperty在我的代码中调用并没有解决问题,它实际上使文本用新行(但不缩进).

任何人都有解决方案,而不需要外部库?

Bor*_*zic 6

您可能还必须指定要缩进的空格量:

transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
Run Code Online (Sandbox Code Playgroud)