Two Laptop Bag*
The moose likes XML and Related Technologies and the fly likes New elements of DOM structure on new lines ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "New elements of DOM structure on new lines ??" Watch "New elements of DOM structure on new lines ??" New topic

New elements of DOM structure on new lines ??

Girish Venkata

Joined: May 24, 2004
Posts: 1

I am using the code below to output a regular DOM structure to an XML file. This code was picked up from the JAVA site and used with very little modification. The problem that I face is basically the following.
Unlike the tutorials which I am following along, the elements that I print to the file are not getting printed onto new lines but instead all of the DOM structure gets printed on a single line. Is there a quick fix around this problem.

Thanks in advance

public static void writeXmlToFile(String filename, Document document) {
try {
// Prepare the DOM document for writing
Source source = new DOMSource(document);

// Prepare the output file
File file = new File(filename);
Result result = new StreamResult(file);

// Write the DOM document to the file
// Get Transformer
Transformer xformer = TransformerFactory.newInstance().newTransformer();
// Write to a file
xformer.transform(source, result);
xformer.setOutputProperty( "indent", "yes" );

} catch (TransformerConfigurationException e) {
System.out.println("TransformerConfigurationException: " + e);
} catch (TransformerException e) {
System.out.println("TransformerException: " + e);
Lasse Koskela

Joined: Jan 23, 2002
Posts: 11962
The code you posted is the only "standard" way of trying to affect the indentation of the printed XML. If you're ok with using parser-specific APIs for this, and if you're using Xerces, take a look at HowToPrettyPrintXmlWithJava in our wiki FAQ.

Author of Test Driven (2007) and Effective Unit Testing (2013) [Blog] [HowToAskQuestionsOnJavaRanch]
Consider Paul's rocket mass heater.
subject: New elements of DOM structure on new lines ??
Similar Threads
Return type recomendation
Generated Xml-File: make available for the user
Deleting child nodes from an xml
How to transform DTD with JAXP
writing updated data in to DOM memory