View RSS Feed

My Java Tips


Rate this Entry
by , 11-03-2011 at 12:55 PM (3062 Views)
We use Structured Query Language (SQL) for querying certain kinds of relational databases. Other less familiar query languages include Object Query Language (OQL) and XQuery. XPath, a query language used for querying XML documents.

Following XPath query finds the titles of all the books in a document whose author is Neal Stephenson:

//book[author="Neal Stephenson"]/title

Following example uses DOM to find all the title elements of books by Neal Stephenson.

Java Code:
ArrayList result = new ArrayList();
NodeList books = doc.getElementsByTagName("book");
for (int i = 0; i < books.getLength(); i++) {
    Element book = (Element) books.item(i);
    NodeList authors = book.getElementsByTagName("author");
    boolean stephenson = false;
    for (int j = 0; j < authors.getLength(); j++) {
        Element author = (Element) authors.item(j);
        NodeList children = author.getChildNodes();
        StringBuffer sb = new StringBuffer();
        for (int k = 0; k < children.getLength(); k++) {
            Node child = children.item(k);
            // really should to do this recursively
            if (child.getNodeType() == Node.TEXT_NODE) {
        if (sb.toString().equals("Neal Stephenson")) {
            stephenson = true;

    if (stephenson) {
        NodeList titles = book.getElementsByTagName("title");
        for (int j = 0; j < titles.getLength(); j++) {


The DOM code is not as generic or robust as the simple XPath expression. It is easy to design and maintain XPath. Unfortunately, XPath is not the Java language. It is also true to say that XPath is not a complete programming language. There are lot of things which are not possible in XPath but possible using SQL. However, it is possible to integrate XPath into Java programs- It means you get benefit of both.

There are APIs available that provides support of Xpath in Java. For example: Xalan and Saxon.

Java 5 has introduced the javax.xml.xpath package to provide an engine and object-model independent XPath library.

Submit "XPath VS DOM" to Facebook Submit "XPath VS DOM" to Digg Submit "XPath VS DOM" to Submit "XPath VS DOM" to StumbleUpon Submit "XPath VS DOM" to Google

Tags: None Add / Edit Tags