Skip to main content

Xpath query and examples

In this post, we'll look at the commonly used XPath queries. We'll be using the following XML file as an example

<bookstore>
  <book category="cooking">
   <title lang="en">Everyday Italian</title>
   <author>Giada De Laurentiis</author>
   <year>2005</year>
   <price>30.00</price>
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title lang="en">XQuery Kick Start</title>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
    <year>2003</year>
    <price>49.99</price>
  </book>
  <book category="web" cover="paperback">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>


/    :   Select Root Element

Using this as XPath query will return the entire document

node    :   Select nodes

e.g. Using "bookstore" will return the bookstore element node with its children

Using this as XPath query will return the entire document


//node    :   Select nodes in the document from the current node matching the selection

e.g. Using "//book" will return the root book element nodes irrespective of its position

  :   Select attributes

e.g. Using "//book/@category" will return the category attribute for book nodes (Note // is used to get the book node irrespective of its position)

e.g. Using "//book[@category]" will return the book nodes having category attribute

e.g. Using "//book[@category="web"]" will return the book nodes with category attribute set to "web"

Examples using Predicates 

"//book[1]" will return the first book node

"/bookstore/book[last()]" will return the last book node which is child of bookstore

"/bookstore/book[position() < 3]" will return the first and second book node

"//*" will return all the nodes (complete document i.e. bookstore as one node, then book element, title element and so on)

"//book[@category="cooking"]/title/text()" will return the text for title element for book with category cooking

"count(//book)" will return the number of book elements










Comments