Convert an org.w3c.dom.Node into a String

ragebiswas picture ragebiswas · Feb 8, 2010 · Viewed 36.1k times · Source

Sorry I'm a Java/XML newbie - and can't seem to figure this one out. It seems it's possible to convert a Document object to a string. However, I want to convert a Node object into a string. I am using org.ccil.cowan.tagsoup Parser for my purpose.

I'm retrieving the Node by something like...

 parser = new org.ccil.cowan.tagsoup.Parser() 

 parser.setFeature(namespaceaware, false)

 Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
 DOMResult domResult = new DOMResult(); 

 transformer.transform(new SAXSource(parser, new InputSource(in)), domResult);
 Node n = domResult.getNode();      

 // I'm interested in the first child, so...
 Node myNode = n.getChildNodes().item(0);

 // convert myNode to string..
 // what to do here?

The answer may be obvious, but I can't seem to figure out from the core Java libraries how to achieve this. Any help is much appreciated!

Answer

Kevin picture Kevin · Feb 8, 2010

You can use a Transformer (error handling and optional factory configuration omitted for clarity):

Node node = ...;
StringWriter writer = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(node), new StreamResult(writer));
String xml = writer.toString();
// Use xml ...