XML XPath

What is XPath?

To navigate through elements and attributes in an XML document, XPath is used as a major element in the XSLT standard which contains a library of standard functions. It is a syntax for defining parts of an XML document that uses path expressions to navigate in XML documents. Along with being a major element in XSLT and XQuery, XPath is also a W3C recommendation.

XPath Path Expressions:

To select nodes or node-sets in an XML document, XPath uses path expressions that look similar to the expressions we see when we work with a traditional computer file system. Along with JavaScript, Java, XML Schema, PHP, Python, C and C++, XPath expressions can be used in a lot of other languages too.

XPath is used in XSLT:

Being a major element in the XSLT standard, XPath knowledge allows us to take great advantage of XSL.

Example:




  
    ABC
    Author Name
    2020
    100.00
  

  
    XQuery Book
    Author 1
    Author 2
    Author 3
    Author 4
    2004
    350.00
  


XPath expressions and the result of the expressions:

Below we are listing some XPath expressions and the result of the expressions:

XPath Expression Result
/bookstore/book[1] The first book element is selected which is the child of the bookstore element.
/bookstore/book[last()] The last book element is selected which is the child of the bookstore element.
/bookstore/book[last()-1] The last but one book element is selected which is the child of the bookstore element.
/bookstore/book[position()<3] The first two book elements are selected which are children of the bookstore element.
//title[@lang] All the title elements are selected which have an attribute named lang.
//title[@lang=’en’] All the title elements are selected which have a “lang” attribute with a value of “en”.
/bookstore/book[price>100.00] All the book elements of the bookstore element are selected which have a price element with a value greater than 100.00.
/bookstore/book[price>100.00]/title All the title elements of the book elements of the bookstore element are selected which have a price element with a value greater than 100.00.