Serialization

One of the most common questions about using DOM is, “I have a DOM tree; how do I write it out to a file?” This question is asked so often because DOM Levels 1 and 2 do not provide a standard means of serialization for DOM trees. While this is a bit of a shortcoming of the API, it provides a great example in using DOM (and as you’ll see in the next chapter, DOM Level 3 seeks to correct this problem). In this section, to familiarize you with the DOM, I’m going to walk you through a class that takes a DOM tree as input, and serializes that tree to a supplied output.

Getting a DOM Parser

Before I talk about outputting a DOM tree, I will give you information on getting a DOM tree in the first place. For the sake of example, all that the code in this chapter does is read in a file, create a DOM tree, and then write that DOM tree back out to another file. However, this still gives you a good start on DOM and prepares you for some more advanced topics in the next chapter.

As a result, there are two Java source files of interest in this chapter. The first is the serializer itself, which is called (not surprisingly) DOMSerializer.java. The second, which I’ll start on now, is SerializerTest.java. This class takes in a filename for the XML document to read and a filename for the document to serialize out to. Additionally, it demonstrates how to take in a file, parse it, and obtain the resultant DOM tree object, represented by the org.w3c.dom.Document class. Go ahead and download ...

Get Java and XML, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.