indent XML text with Transformer

删除回忆录丶 提交于 2019-12-01 11:40:14

问题


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:


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

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


来源:https://stackoverflow.com/questions/1082886/indent-xml-text-with-transformer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!