javacodex.com
Java Examples
Java Examples
memu home questions

DOM XML Parser Example

This example shows you how to read an XML file via DOM (Document Object Model) XML parser.

Source: (ReadXMLFile.java)

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.File;
 
public class ReadXMLFile {
 
   public static void main(String argv[]) {
 
      try {
 
         File file = new File("./file.xml");
 
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         Document doc = db.parse(file);
         doc.getDocumentElement().normalize();
 
         System.out.println("Root Element: " + doc.getDocumentElement().getNodeName());
 
         NodeList list = doc.getElementsByTagName("book");
 
         for (int i = 0; i < list.getLength(); i++) {
 
            Node node = list.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
 
               Element e = (Element) node;
 
               System.out.println("Book ID : " + 
                     e.getAttribute("id"));
 
               System.out.println("  Title : " + 
                     e.getElementsByTagName("title").item(0).getTextContent());
 
               System.out.println("  Price : " + 
                     e.getElementsByTagName("price").item(0).getTextContent());
 
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
 

Output:

$ cat file.xml
<?xml version="1.0"?>
<inventory>
   <book id="1001">
      <title>The Cat in the Hat</title>
      <author>Dr. Seuss</author>
      <price>10.00</price>
   </book>
   <book id="2001">
      <title>Adventures of Huckleberry Finn</title>
      <author>Mark Twain</author>
      <price>20.00</price>
   </book>
</inventory>

$ java ReadXMLFile 
Root element: inventory
Book ID : 1001
  Title : The Cat in the Hat
  Price : 10.00
Book ID : 2001
  Title : Adventures of Huckleberry Finn
  Price : 20.00

Contact: javacodex@yahoo.com