Xpath query and examples

October 19, 2018 2 min read xpath

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

Everyday ItalianGiada De Laurentiis200530.00Harry PotterJ K. Rowling200529.99XQuery Kick StartJames McGovernPer BothnerKurt CagleJames LinnVaidyanathan Nagarajan200349.99Learning XMLErik T. Ray200339.95

/ : 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