*
The moose likes XML and Related Technologies and the fly likes DOM contents to string instead of a file... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "DOM contents to string instead of a file..." Watch "DOM contents to string instead of a file..." New topic
Author

DOM contents to string instead of a file...

Mike Cronin
Greenhorn

Joined: Apr 17, 2002
Posts: 25
Hi all,
I would like to write the contents of a DOM to a string instead of to a file. Does any one have an example of doing this?
Thanks in advance.
Mike Cronin
Data On Call
Lasse Koskela
author
Sheriff

Joined: Jan 23, 2002
Posts: 11962
    
    5
JavaRanch Wiki to the rescue


Author of Test Driven (2007) and Effective Unit Testing (2013) [Blog] [HowToAskQuestionsOnJavaRanch]
Mike Cronin
Greenhorn

Joined: Apr 17, 2002
Posts: 25
Hey Lasse,
Thanks for the quick response!
I went with the following code which works great!

import org.apache.xml.serialize.*;
...
private void domToString(Document doc) throws Exception{
try {
// Serialize the DOM
OutputFormat format = new OutputFormat(doc);
// Establish a new StringWriter object
StringWriter sw = new StringWriter();
// Establish a XMLSerializer object
XMLSerializer serial = new XMLSerializer(sw, format);
// Set the XMLSerializer as a DOM Serializer
serial.asDOMSerializer();
// Serialize the DOM
serial.serialize(doc.getDocumentElement());
// Store the DOM contents to a string
requestXML = sw.toString();
}
catch (Exception e) {
System.out.println("Error in domToString method " + e.getMessage());
throw new Exception ("Error in domToString method" + e);
}
}

Do you have an opion on using the javax.xml libraries as opposed to org.apache.xml?
Thanks again for the quick response !
Mike Cronin
Data On Call
Lasse Koskela
author
Sheriff

Joined: Jan 23, 2002
Posts: 11962
    
    5
Originally posted by Mike Cronin:
Do you have an opion on using the javax.xml libraries as opposed to org.apache.xml?
Only the obvious: org.apache.xml.* is not a standard while javax.xml.* is... If you're ok with relying on having Xerces as your parser, the XMLSerializer probably works better than the Transformer trick, though.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: DOM contents to string instead of a file...