Although XPath and XQuery can achieve some of the same functionality, XPath is simpler and XQuery is more powerful and flexible. XPath is perfect for many queries. For example, creating an unordered list of phone numbers from some of the records in an XML document is easiest to use with XPath. However, if you need expressions that express more complex record selection criteria, convert a result set, or make a recursive query, you need to use XQuery.
Xpath
XPath is a domain-specific language (domain-specific Language, DSL) and quickly becomes an important part of other, more common languages. Programming languages combine XPath with modules and classes, sometimes even directly into the grammar of a language. This situation is similar to the case of a previous regular expression.
XPath is popular because of the amount of time and effort that XPath can save developers from extracting specific data from an XML document. Even people who have never touched XPath can quickly take advantage of their powerful capabilities. For example, the XML fragment in Listing 1.
Listing 1. XML Document
<users>
<user>
<name>
<first>Lola</first>
<last>Solis</last>
</name>
<age>2</age>
</user>
<user>
<name>
<first>Nina</first>
<last>Serafina</last>
</name>
<age>4</age>
<visits>
<first>2008-01-15</first>
<last>2008-02 -15</last>
</visits>
</user>
<user>
<name>
<first>Tracy</first>
<last>Keller</last>
</name>
<age>35</age>
</user>
</users>
Use the following XPath expression if you need to get a list of the names of teenagers in your document.
Listing 2. Select the last name of a user under 18 years of age
/user[age lt 18]/name/last/text()
(: Result
Solis
Serafina
:)