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;
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();
}
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:
Thanks, I needed that!
Hi, I was having a lot of trouble with converting node to string... your code solved it very simply...Thanks for your help...
Thanks! Been fighting this for the past couple hours and hit on the magic search terms ;)
Thanks for the function. I could not figure this out.
Extremely useful piece of code. Thanks for sharing it.
Thanks buddy....
Thanks!
Thanks!
You function was extremely useful. Thanks a lot!
Thanks a lot, I need it!!!
saved me a ton of time, thanks.
Post a Comment