/** * A simple DOM parser. This parser parses the file whose name is * passed as an argument. It then merely prints out the node type, name * and value for the Document node. * * @author Nauman Chaudhry * @date Apr 6, 08 */ // Note that DocumentBuilder and DocumentBuilderFactory are part // of JAXP and hence appear in the package: javax.xml.parsers import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; // Document interface is part of DOM API and appears in org.w3c.dom import org.w3c.dom.Document; public class Ex1SimpleDom { public static void main(String[] args) throws Exception { // First get a document builder factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // Now get a document builder DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); return; } // Call the parse method on DocumentBuilder. This returns an object // of type Document Document myDoc = db.parse(args[0]); // Now we just print the nodeType, nodeName and nodeValue of the // document node. Look at the JavaDoc for the Node interface and // you will see that for Document node: // name = "#document" (i.e., a fixed string) // value = null // The utility of Document node is that from it we can get the DOCTYPE declaration // as well as the Root Element and then traverse the document System.out.println(" node type = " + myDoc.getNodeType() + " name = " + myDoc.getNodeName() + " value = " + myDoc.getNodeValue()); } }