One way to get a string representation of the DOM tree (the
XML document) uses an object of type LSSerializer (LS means
Load and Save).
We obtain this LSSerializer using the following mysterious
1. Using the Document object, get the DOMImplementation
object that handles this document.
DOMImplementation imp = doc.getImplementation();
2. Get a DOMImplementationLS object using the getFeature
method of the DOMImplementation with two parameters,
feature = "LS" and version = "3.0".
DOMImplementationLS implLS =
3. Using the instance method createLSSerializer for the
DOMImplementationLS object, we get an LSSerializer object.
LSSerializer ser = impLS.createLSSerializer();
4. The LSSerializer object knows how to write the tree.
We use the method that creates a string.
String out = ser.writeToString(doc);
Note that the string produced by ser.writeToString has no
ignorable white space, which mean there are no new lines and
To see the XML document with new lines and indenting, we can
run it through the linux utility xmllint with the --format option.
If we want to look at the file in a text editor, we must change the
encoding to "UTF-8" before formatting with xmllint.