Quering an XML document with a fixed XPath expression

11 July 2008

I will present a complete program to query an XML document with a fixed XPath expression.

The method can throw several exceptions that must be declared in try- catch blocks. Do proper exception handling.

import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
 
public class XPathExample {
 
  public static void main(String[] args) 
   throws ParserConfigurationException, SAXException, 
          IOException, XPathExpressionException {
 
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true); // never forget this!
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("books.xml");
 
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr 
     = xpath.compile("//book[author='Neal Stephenson']/title/text()");
 
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getNodeValue()); 
    }
 
  }
 
}

Just try the above code and play with it.

del.icio.us:Quering an XML document with a fixed XPath expression  digg:Quering an XML document with a fixed XPath expression  spurl:Quering an XML document with a fixed XPath expression  wists:Quering an XML document with a fixed XPath expression  simpy:Quering an XML document with a fixed XPath expression  newsvine:Quering an XML document with a fixed XPath expression  blinklist:Quering an XML document with a fixed XPath expression  furl:Quering an XML document with a fixed XPath expression  reddit:Quering an XML document with a fixed XPath expression  fark:Quering an XML document with a fixed XPath expression  blogmarks:Quering an XML document with a fixed XPath expression  Y!:Quering an XML document with a fixed XPath expression  smarking:Quering an XML document with a fixed XPath expression  magnolia:Quering an XML document with a fixed XPath expression  segnalo:Quering an XML document with a fixed XPath expression  gifttagging:Quering an XML document with a fixed XPath expression

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Quering an XML document with a fixed XPath expression

Leave a Reply