Java Reference
In-Depth Information
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
The newInstance() method is a static method in the factory 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 the change to parser you are using without modifying or recompiling your code. You use the
factory object to create a DocumentBuilder object that encapsulates a DOM parser:
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch(ParserConfigurationException e) {
e.printStackTrace();
}
As we shall see, when a DOM parser reads an XML document, it makes it available in its entirety as an
object of type Document . The name of the class that encapsulates a DOM parser has obviously been chosen
to indicate that it can also build new Document objects. A DOM parser can throw exceptions of type
SAXException and parsing errors are handled in essentially the same way in DOM and SAX2. The
DocumentBuilderFactory , DocumentBuilder , and ParserConfigurationException classes are
all defined in the javax.xml.parsers package. Let's jump straight in and try this out for real.
Try It Out - Creating an XML Document Builder
Here's the code to create a document builder object:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
public class TryDOM {
public static void main(String args[]) {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
}
catch(ParserConfigurationException e) {
e.printStackTrace();
System.exit(1);
}
System.out.println("Builder Factory = " + builderFactory +"\nBuilder = "
+ builder);
}
}
I got the output:
Builder Factory = org.apache.xerces.jaxp.DocumentBuilderFactoryImpl@430b5c
Builder = org.apache.xerces.jaxp.DocumentBuilderImpl@9ed927
Search WWH ::




Custom Search