Monday, April 25, 2011

XPath Example

XPath is a query language for XML defined by the W3C. It can:

  • Select nodes in a XML document
  • Compute values from the content of an XML document.
XPath 1.0 became a W3C recommendation in November 1999 . XPath 2.0 became a W3C recommendation in January 2007. In XPath 2.0 every value has become a sequence. XPath 2.0 has a richer type set.

An example please?

No problem. Let's start with some XML.



The XML represents some books in a library. Suppose you wish to query this XML to see the names of the books that Brian Smith has wrote. Now you don't want the hassle of converting the XML to book objects and filtering through them yourself just to get the names. So you decide to use XPath. Here's how you'd do it.

Other points worth pointing out:
  1. An XPath expression is not thread-safe and not reentrant. In other words, it is the application's responsibility to make sure that one XPathExpression object is not used from more than one thread at any given time, and while the evaluate method is invoked, applications may not recursively call the evaluate method.
  2. XPathConstants.NODESET is a XPath 1.0 type. 
  3. There are some tools out there to help you figure out what your XPath expression should be. For example XmlToolBox

No comments:

Post a Comment