Tuesday, 19 August 2008

Java Node to String Conversion

When trying to convert a org.w3c.dom.Node to a string, I initial tried using toString(). I assumed toString() would give me text content of the XML contained in the node but it was not going to be that easy today, it gave me some kind of pointer gobbledeguck back.

OK then, with some investigation, I found that toString() shouldn't really be relied upon, so I have written the following method using StringWriter and Transform methods.

import org.w3c.dom.Node;

import java.io.StringWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;


private String nodeToString(Node node) {
StringWriter sw = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException te) {
System.out.println("nodeToString Transformer Exception");
}
return sw.toString();
}

Node to String...Converted.

11 comments:

Glenn Murray said...

Thanks, I needed that!

kiran said...

Hi, I was having a lot of trouble with converting node to string... your code solved it very simply...Thanks for your help...

Gary Teichrow said...

Thanks! Been fighting this for the past couple hours and hit on the magic search terms ;)

Ben said...

Thanks for the function. I could not figure this out.

technicalmumbojumbo said...

Extremely useful piece of code. Thanks for sharing it.

...aSif... said...

Thanks buddy....

Marnix Klooster said...

Thanks!

Carl said...

Thanks!

Mehdi said...

You function was extremely useful. Thanks a lot!

JRHuergo said...

Thanks a lot, I need it!!!

Ernest Koe said...

saved me a ton of time, thanks.