I had a unique situation where I needed to parse an XML document using Java, and I needed to preserve some of the XML in the document. I am so used to parsing XML documents using Node and Element names etc, I could not find a method on the Document/Node or Element objects that would act like a toString() on a node.
Ends up you need to send it through a Transformer. Here is some example code that you can use on any node or element on the DOM.
TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
The replaceAll is completely optional. This simply removes CR/LFs from the XML document, but if you remove that, you can view the XML element as is, children and all.
The doc in bold can be any node on the XML document. In my case, my node was in the middle of the DOM, so I did not want a full string representation of the complete XML document, I just wanted a node.