Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

New elements of DOM structure on new lines ??

Girish Venkata
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 11962
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic