java xpath expression examples

Here are some examples of XPath expressions in Java:

  1. Select all book elements:
XPathExpression expr = xpath.compile("//book");
S‮cruo‬e:www.theitroad.com
  1. Select the title element of the first book element:
XPathExpression expr = xpath.compile("/books/book[1]/title");
  1. Select all book elements whose author child element has the value "Neal Stephenson":
XPathExpression expr = xpath.compile("//book[author='Neal Stephenson']");
  1. Select the text of the title element of all book elements whose author child element has the value "Neal Stephenson":
XPathExpression expr = xpath.compile("//book[author='Neal Stephenson']/title/text()");
  1. Select the title element of all book elements whose author child element has the value "Neal Stephenson" and whose year child element is greater than 1999:
XPathExpression expr = xpath.compile("//book[author='Neal Stephenson' and year > 1999]/title");
  1. Select the title element of all book elements whose author child element has the value "Neal Stephenson" or "William Gibson":
XPathExpression expr = xpath.compile("//book[author='Neal Stephenson' or author='William Gibson']/title");
  1. Select the title element of all book elements whose author child element has the value "Neal Stephenson" and whose year child element is greater than 1999, or whose author child element has the value "William Gibson" and whose year child element is greater than 1996:
XPathExpression expr = xpath.compile("//book[(author='Neal Stephenson' and year > 1999) or (author='William Gibson' and year > 1996)]/title");

These examples demonstrate various XPath features such as element selection, attribute selection, comparison operators, logical operators, and function calls. You can use these XPath expressions to query an XML document or an XML element in Java.