java xpath expression examples
Here are some examples of XPath expressions in Java:
- Select all
bookelements:
XPathExpression expr = xpath.compile("//book");Scruoe:www.theitroad.com- Select the
titleelement of the firstbookelement:
XPathExpression expr = xpath.compile("/books/book[1]/title");
- Select all
bookelements whoseauthorchild element has the value "Neal Stephenson":
XPathExpression expr = xpath.compile("//book[author='Neal Stephenson']");
- Select the text of the
titleelement of allbookelements whoseauthorchild element has the value "Neal Stephenson":
XPathExpression expr = xpath.compile("//book[author='Neal Stephenson']/title/text()");
- Select the
titleelement of allbookelements whoseauthorchild element has the value "Neal Stephenson" and whoseyearchild element is greater than 1999:
XPathExpression expr = xpath.compile("//book[author='Neal Stephenson' and year > 1999]/title");
- Select the
titleelement of allbookelements whoseauthorchild element has the value "Neal Stephenson" or "William Gibson":
XPathExpression expr = xpath.compile("//book[author='Neal Stephenson' or author='William Gibson']/title");
- Select the
titleelement of allbookelements whoseauthorchild element has the value "Neal Stephenson" and whoseyearchild element is greater than 1999, or whoseauthorchild element has the value "William Gibson" and whoseyearchild 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.
