Magazine
 
JAXP API using DOM Parser

Main classes of javax.xml.parsers package for the DOM:

Classes Description
DocumentBuilder Defines the API to obtain DOM
Document instances from an
XML document.
DocumentBuilderFactory Defines a factory API that enables applications to
obtain a parser that produces
DOM object trees from XML documents

The diagram here shows the JAXP APIs to process xml document using the DOM parser:

Understanding DOM Parser

At the very first, javax.xml.parsers.Document BuilderFactory class creates the instance of DocumentBuilder. Through which it produces a Document (a DOM) that conforms to the DOM specification. The System property determines the builder at the run time using javax.xml.parsers.DocumentBuilderFactory (it
selects the factory implementations to produce the builder). The platform’s default value i.e. system property can be overridden from the command line.

Another method of DocumentBuilder as newDocument() can also be used implementing org.w3c.dom.Document interface that creates an empty Document.

 

Alternatively, one of the builder’s parse methods can be used to create a Document from existing XML data. As a result, a DOM tree like that shown in the diagram.

Creating Blank DOM Document
The following code creates a blank document:

//Create instance of DocumentBuilderFactory
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
//Get the DocumentBuilder
DocumentBuilder parser =
factory.newDocumentBuilder();
//Create blank DOM Document
Document doc =
parser.newDocument();

The class DocumentBuilderFactory is responsible for creating new DOM parsers. The instance of the class DocumentBuilder is used to create a blank document. The newDocument() method of the class returns a blank DOM document.

Creating DOM Child Elements

Once new document has been created, you can add the element to it. First element of the document is called the root element; another elements added to the document are called child elements of the root.

The following steps generate a DOM document having root and child elements.

(1) Creating the root element

As you have seen above that how to create a blank DOM document using DocumentBuilder object. The following code creates a blank document.

//Create blank DOM Document
Document doc = docBuilder.newDocument();

The createElement method is used to create the root element and appendChild method is

Mar 2008 | Java Jazz Up | 19

 
previous
index
next
 
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59,

Download PDF