Sign in to follow this  
CodeMachine

[java] XML output - Indent problem

Recommended Posts

Hi I've problem indenting the XML while saving a Document to file. The resulting XML is not indented. Code:
try {
 // Create document.
 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
 
 // Create nodes.
 Element a = doc.createElement("A");
 Element b = doc.createElement("B");
 Element c = doc.createElement("C");
 c.setTextContent("Indent Test");
 
 // Append nodes.
 doc.appendChild(a);
 a.appendChild(b);
 b.appendChild(c);
 
 // Save to file.
 TransformerFactory tf = TransformerFactory.newInstance();
 Transformer t = tf.newTransformer();
 t.setOutputProperty("method", "xml");
 t.setOutputProperty("encoding", "UTF-8");
 t.setOutputProperty("indent", "yes");
 t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
 t.transform(new DOMSource(doc), new StreamResult(new FileOutputStream("Test.xml")));
} catch(Exception e) {
 // ...
}


Result:
<?xml version="1.0" encoding="UTF-8"?>
<A>
<B>
<C>Indent Test</C>
</B>
</A>


Why isn't the result indented? I've set properties to the Transformer, both "indent" and "indent-amount", but I have no indent at all. Why? Do I manually have to traverse the Document and print all data to a file myself? / Kind Regards

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this