Menu

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

Goal

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

Description

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:

Explanations

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.