org.w3c.dom.Node to java.lang.String


To print the full XML of a given org.w3c.dom.Node element in Java


Recently, while working in a given project, I had the need to see the full details of a given Node element so that I could check exactly what was the XML of the element that I got when invoking a specific Web service method whose results were lists of Nodes (actually, they were org.w3c.dom.Element instances). This recipe provides the necessary code I wrote in order to print the node details.

How to

The following method function, which was more or less the code I wrote to solve my issue, will make it possible to print the XML node’s details:

public static String nodeToString(final Node node, final boolean omitXMLDeclaration) {
  final StringWriter writer = new StringWriter();
  try {
    final Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration ? "yes" : "no");
    t.setOutputProperty(OutputKeys.INDENT, "yes"); // indent to show results in a more human readable format
    t.transform(new DOMSource(node), new StreamResult(writer));
  } catch(final TransformerException e) {
  return writer.toString();


And it’s done. So, to summarize things up, all we have to do to print the node details is to obtain an instance of javax.xml.transform.Transformer, configure the necessary (if any) output properties, and transform the DOMSource of the node into a SteamResult with a new instance of StringWriter whose string representation, obtained with the call to the toString() method, will be the method’s result.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s