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