University of Cincinnati logo and link  
Reading an XML file
 
  UC ingot
 
  • Start with a DocumentBuilder object that you get from the DocumentBuilderFactory.

  • DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = factory.newDocumentBuilder();
    • Use the setValidating method of DocumentBuilderFactory if you want to have the resulting builder validate your XML.  This is false by default.  There are a number of other options you can set with methods like this.  See the API documentation for details.
  • Now, you can get a reference to a File, URL, or InputStream, send it to the parse method of DocumentBuilder, and get your Document back.
  • The document object that results is a representation of your XML document.
    • getDocumentElement returns an Element which represents the root element of the document.  Interface Element extends interface Node
      • We can get, set, and remove attributes with an Element object.
      • We can get children Nodes from the root element with the getChildNodes method of the Node interface.  This returns a NodeList, which is essentially a collection of children nodes.
      • NodeList has two simple methods - getLength and item.
 Using Nodes 



.