You can use XPathExpression from javax.xml.xpath package to create and execute XPATH expression in Java. Java API provides javax.xml.xpath package, which contains classes like Xpath, XpathFactory to work with XPATH and XML documents. By the way this is third article on Xpath, In last couple of tutorials e.g. XPATH examples to select values using attributes and my XPATH notes for Java programmer, we have seen basics of Xpath expression from XML and Java point of view. Anyone who has work with XML technologies in Java knows importance of XPATH, it is one the most useful technology to retrieve selected data from XML files. XPATH is like SQL which is used to retrieve data from relational database. Many back-office and middle-office Java application which transfers data in form of XML documents makes extensive use of XPATH expression to retrieve value for printing or for decision making. Though there are lot of open source XML libraries are available to assist with Java and XML development e.g. XML Beans. I personally prefer to use standard Java API if functionality is available there. In this Java tutorial we will learn how to create XPath expression in Java program and retrieving values from XPATH e.g. text, numbers and boolean values, which is critical for programming flow.
Java XPATH expression Example
Creating XPATH expression is simple, just navigate to the node you want to retrieve by putting "/" like in our example if we want to retrieve models of each smartphone than we will write Xpath expression as /smartphones/smartphone/model. Apart from navigating to desired node in Xpath expression we have also used utility method text() to retrieve text and count() to count number of matching results. Java classes from java.xml.xpath package e.g. XPath, XPathFactory and XPathExpression is used to create and evaluate Xpath in Java programming language.
That’s all on How to create and evaluate XPath expression in Java . We have seen How to select XML elements value as text using text() function and counted matching elements using count() function. Xpath is real interesting stuff and once you get the basics, its very easy to work with Xpath both in XML editors and Java programming language.
Other Java and XML tutorials for Java programmers