
The easiest way to get a DOM Tree is to parse an XML file using a DocumentBuilder . Then you can traverse the Document object and extract what you need. The JAXP framework provides several classes to do this but the important ones are:
All you need to do is to invoke DocumentBuilderFactory.newInstance() and then using this instance, to get a new DocumentBuilder - ( newDocumentBuilder ()). Finally, use the DocumentBuilder instance to parse an XML file, using DocumentBuilder.parse(InputSource) . Further, you can specify whether you want your DocumentBuilder to be validating - DocumentBuilderFactory.setValidating(boolean) , or to be namespace-aware - DocumentBuilderFactory.setNamespaceAware(boolean).
public class JAXPDOMExample {
public static void main(String args[]) {
try {
String xml= "data/rich_ii.xml";
//get a DocumentBuilderFactory from the underlying
//implementation
DocumentBuilderFactory factory;
ClassLoader oldLoader;
try {
//Although in standalone applications like this one, the classloader
//of the JAXPDOMExample class and the thread context classloader
//are the same, for the sake of completeness preset the loader
oldLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(JAXPDOMExample.class.getClassLoader());
factory = DocumentBuilderFactory.newInstance();
} finally {
Thread.currentThread().setContextClassLoader(oldLoader);
}
factory.setValidating(true);
//get a DocumentBuilder from the factory
DocumentBuilder builder = factory.newDocumentBuilder();
//parse the document
Document document = builder.parse(xml);
DOMTraverser domTester = new DOMTraverser();
domTester.traverse1(document);
} catch (Exception e) {
//if there was some error while parsing the file
e.printStackTrace();
}
}