indent XML text with Transformer

2020-03-31 04:40发布

I'm writing an XML file with the following code:

Source source = new DOMSource(rootElement);
Result result = new StreamResult(xmlFile);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);

and this is the output file:

<?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>
...

I want this file to be indented, for example:

<?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>
...

the call to setOutputProperty in my code doesn't solve the problem, it actually makes the text with new lines (but not indented).

anyone has a solution to this, without the need of external libraries?

1条回答
Evening l夕情丶
2楼-- · 2020-03-31 05:12

You may have to specify the amount of spaces to indent as well:

transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
查看更多
登录 后发表回答