• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

DOM contents to string instead of a file...

 
Mike Cronin
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11962
5
 
Mike Cronin
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic