Document, Element and Attr Interface ALL extend from Node Interface.
The Document interface represents the entire HTML or XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data.
The Element interface represents an element in an HTML or XML document. Elements may have attributes associated with them;
book.xml - the XML file to be read
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
<title>DST</title>
<publisher>ORiley</publisher>
<price>10.00</price>
</book>
<book>
<title>News</title>
<publisher>NYT</publisher>
<price>12.00</price>
</book>
</bookstore>
ReadXML.java - reads book.xml
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXML {
public static void main(String[] args) {
try {
File fXmlFile = new File("book.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
// get root element
System.out.println("Root element : "
+ doc.getDocumentElement().getNodeName());
// node list with tag ame "book"
NodeList nList = doc.getElementsByTagName("book");
for (int i = 0; i < nList.getLength(); i++) {
// get a node from node list
Node node = nList.item(i);
// if the node is an element, print its title, publisher, price
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) node;
System.out.println("title: "
+ getTagValue("title", eElement));
System.out.println("publisher: "
+ getTagValue("publisher", eElement));
System.out.println("price: "
+ getTagValue("price", eElement));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// read the tag value from an Element
private static String getTagValue(String tag, Element elem) {
NodeList nList = elem.getElementsByTagName(tag).item(0).getChildNodes();
Node nValue = (Node) nList.item(0);
return nValue.getNodeValue();
}
}
Reference:
http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
http://docs.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/Node.html
http://docs.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/Element.html
http://docs.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/Document.html