Skip to content
XML

XPath

Path expressions for selecting nodes.

By EZ4Code Team
xpathquery

Code

<!-- Source document -->
<library>
  <book id="b1" category="fiction">
    <title lang="en">Dune</title>
    <author>Frank Herbert</author>
  </book>
  <book id="b2" category="science">
    <title lang="en">Cosmos</title>
    <author>Carl Sagan</author>
  </book>
</library>

<!-- XPath expressions:
  /library/book[1]              first book
  //author                      all authors anywhere
  /library/book[@id='b2']       book whose id is b2
  //title[@lang='en']           titles with lang=en
  /library/book[@category='science']/title
-->

Explanation

XPath selects nodes from an XML document using path expressions much like filesystem paths. Predicates in square brackets filter by position or attributes, and the double slash // searches recursively from the root. XPath underpins XSLT, XQuery, and many XML testing libraries.

More XML Snippets