!--a11y-->
Building DOM Trees Through
Parsing 
The easiest way to get a DOM Tree is to parse a 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. Here are two important classes related to this process:
· javax.xml.pasers.DocumentBuilderFactory
· javax.xml.DocumentBuilder
In general, all you need to do is to invoke DocumentBuilderFactory.newInstance() in order to get an instance of the DocumentBuilderFactory. Then you can use this instance to get a new DocumentBuilder – ( newDocumentBuilder()). Finally, use the DocumentBuilder instance to parse an XML file, using DocumentBuilder.parse(InputSource. You can further specify whether you want your DocumentBuilder to be validating - DocumentBuilderFactory.setValidating(boolean), or to be namespace-aware - DocumentBuilderFactory.setNamespaceAware(boolean).
A short example for building trees through parsing is presented below:

|
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 = DocumentBuilderFactory.newInstance(); 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(); } } |
