Document object to String object (Java Code)

Converting a Document object to a String object in Java is an issue I’ve run into a couple times at work. I wanted to see the output of a WebService call response that was in XML in the console. Here’s a quick code snippet I found that handles this:

// xmlDoc is the Document object

DOMSource domSource = new DOMSource(xmlDoc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);

System.out.println(writer.toString());

 

 


Posted

in

by

Tags:

Comments