1

我正在使用以下代码编写一个 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并不能解决问题,它实际上使文本带有新行(但没有缩进)。

任何人都可以解决这个问题,而不需要外部库?

4

1 回答 1

6

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

transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
于 2009-07-04T20:21:44.553 回答