Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Converting DOM tree into String 2

Status
Not open for further replies.

BTCMan

Programmer
Jun 17, 2005
21
BR
Hi all,

does anybody knows how to convert an org.w3c.dom.Document into a String ?? (basically I want to log the dom tree into a string object not a file). Thanks

BTCMan
 
You can use the javax.xml.transform package.
Its fairly self-explanatory :

Code:
// To transform the Document to a stream
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

....

Document doc ...

TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamResult result = new StreamResult(baos);
transformer.transform(source, result);

String docString = new String(baos.toByteArray());

This code throws a bunch of exceptions, so you'll need to add in error handling etc.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top