4

I am trying to create XML from Java and am having problems with indenting. In the following code you can see OutputKeys.INDENT set to yes...

        //set up a transformer
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        //create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
        String xmlString = sw.toString();

        //print xml
        System.out.println(xmlString);

but it seems to have no affect, the output is:

<dataset id="1"><br>
<path></path><br>
<session id="1"><br>
<method><br>
<timestamp>a timestamp</timestamp><br>
<signiture><br>
<classPath></classPath><br>
<name>methodName</name><br>
<declarationType>String</declarationType><br>
<parameters><br>
<parameter>String</parameter><br>
<parameter>int</parameter><br>
</parameters><br>
</signiture><br>
<arguments><br>
<argument>SomeValue</argument><br>
<argument>AnotherValue</argument><br>
</arguments><br>
<return>ReturnValue</return><br>
</method><br>
</session><br>
</dataset><br>
Smern
  • 18,746
  • 21
  • 72
  • 90
  • 1
    and here's another one: http://stackoverflow.com/questions/1384802/java-how-to-indent-xml-generated-by-transformer – Anon Apr 21 '11 at 20:28

2 Answers2

6

Try to set indent-amount, AFAIK the default is 0.

trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4")
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
0
Document doc;

.....

TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc), new StreamResult(new File("filename.xml")));
transformer.transform(new DOMSource(doc), new StreamResult(System.out));
iCrazybest
  • 2,935
  • 2
  • 24
  • 24