Java Reference
In-Depth Information
Chapter 23
Creating and Modifying XML Documents
WHAT YOU WILL LEARN IN THIS CHAPTER:
• What the Document Object Model is
• How you create a DOM parser
• How you access the contents of a document using DOM
• How you can create and update a new XML document
• What the Extensible Stylesheet Language (XSL) is
• How the Extensible Stylesheet Language Transformation (XSLT) language relates to XSL
• How you can use a Transformer object to read and write XML files
• How to modify Sketcher to store and retrieve sketches as XML documents
In this chapter you explore what you can do with the Document Object Model (DOM) application program
interface (API). As I outlined in the previous chapter, DOM uses a mechanism that is completely different
from Simple API for XML (SAX). As well as providing an alternative mechanism for parsing XML docu-
ments, DOM also adds the capability for you to modify them and create new ones. You also make a short
excursion into XSLT and apply it with DOM in Sketcher. By the end of this chapter you have a version of
Sketcher that can store and retrieve sketches as XML files.
THE DOCUMENT OBJECT MODEL
As you saw in the previous chapter, a DOM parser presents you with a Document object that encapsulates an
entire XML structure. You can call methods for this object to navigate through the document tree and process
the elements and attributes in whatever way you want. This is quite different from SAX, but there is still quite
a close relationship between DOM and SAX.
The mechanism for getting access to a DOM parser is very similar to what you used to obtain a SAX
parser. You start with a factory object that you obtain like this:
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
The newInstance() method is a static method in the javax.xml.parsers.DocumentBuilderFactory
class for creating factory objects. As with SAX, this approach of dynamically creating a factory object that
you then use to create a parser allows you to change the parser you are using without modifying or recompil-
ing your code. The factory object creates a javax.xml.parsers.DocumentBuilder object that encapsulates
a DOM parser:
Search WWH ::




Custom Search