The code snippet on the right displays a DOM parser that prints the root element of the example.xml XML document. Creating a DOM parser primarily involves specifying the DOM API, creating a parser object, and parsing the XML document.
- Specifying the DOM API
To write a program that uses DOM parsing, you must first include the required packages in your source code. For example:
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
- Creating a parser object
The parser object represents the DOM parser and is used to parse an XML document. In the following code, the db object is the DocumentBuilder object that represents the parser object:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
- Parsing the XML document
The parser object implements the methods to read the XML document and to create a DOM tree. In the following code, the db object implements the parse method to parse the example.xml XML document:
doc = db.parse(new File ("example.xml"));
After parsing the document, you can specify methods that can manipulate the DOM tree. The following code specifies the method to print the root element of the XML document:
Element rootelement = doc.getDocumentElement();
System.out.println(“The root element is “+rootelement.getNodeName());
|