This section provides a tutorial example on how to write an XML file parser, DOMParser.java, with the org.w3c.dom.Document class included in JDK.
What is DOM (Document Object Model)? DOM is
an Application Programming Interface (API) that represents an XML file
as a document object, which allows application programs to manage the information contained
in the document object.
DOM has been implemented in Java in J2SDK 1.4.1_01, which is already installed on my
system. So I am ready to play with XML files through DOM in Java.
Here is a program to show how different packages are used together to parse
an XML file into a DOM document object:
/**
* DOMParser.java
* Copyright (c) 2002 by Dr. Herong Yang
*/
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
class DOMParser {
public static void main(String[] args) {
try {
File x = new File(args[0]);
DocumentBuilderFactory f
= DocumentBuilderFactory.newInstance();
System.out.println(f.toString());
DocumentBuilder b = f.newDocumentBuilder();
System.out.println(b.toString());
Document d = b.parse(x);
System.out.println(d.toString());
DOMImplementation i = d.getImplementation();
System.out.println(i.toString());
} catch (ParserConfigurationException e) {
System.out.println(e.toString());
} catch (SAXException e) {
System.out.println(e.toString());
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
javax.xml.parsers.DocumentBuilderFactory.newInstance() method is used to
create a new fatory instance using a factory implementation from the
org.apache.crimson.jaxp.* package.
javax.xml.parsers.DocumentBuilder.newDocumentBuilder() method is used to
create a new builder instance using a builder implementation from
org.apache.crimson.jaxp.* package.
javax.xml.parsers.DocumentBuilder.parse() method is used to
parse the XML file into an org.w3c.dom.Document object implemented with
org.apache.crimson.tree.XmlDocument class.