cd1
cd1

Reputation: 16534

indent XML text with Transformer

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?

Upvotes: 1

Views: 5422

Answers (1)

Boris Terzic
Boris Terzic

Reputation: 10948

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

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

Upvotes: 6

Related Questions