View RSS Feed

My Java Tips

Quering an XML document with a fixed XPath expression

Rate this Entry
by , 11-01-2011 at 06:22 PM (931 Views)
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.

Java Code:
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.

Submit "Quering an XML document with a fixed XPath expression" to Facebook Submit "Quering an XML document with a fixed XPath expression" to Digg Submit "Quering an XML document with a fixed XPath expression" to del.icio.us Submit "Quering an XML document with a fixed XPath expression" to StumbleUpon Submit "Quering an XML document with a fixed XPath expression" to Google

Tags: None Add / Edit Tags
Categories
XML

Comments