Tutorial On How to Use Xpath on Xml File Or String in Java

Posted on the 16 February 2013 by Abhishek Somani @somaniabhi
Xpath is a W3C's XSLT standard to navigate through the Xml Document . for example consider this sample xml file for auction . each auction contains list of bids apart from other details
<""""""><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> Now if you want to access first bid price in bids then the xpath would be
/auction/bids/bid[0]/price
Java provides xpath support to navigate through the xml document .
classes which are required for applying xpath are following :
 javax.xml.xpath.XPath;
 javax.xml.xpath.XPathConstants;
 javax.xml.xpath.XPathExpressionException;
 javax.xml.xpath.XPathFactory; 
org.w3c.dom.NodeList; 
org.xml.sax.InputSource; 
  First , get instance of XPath from XPathFactory
  Create an InputSource instance from InputStream of xml file .
now get the desired value by entering xpath expresion like this
You can specify required constants from XPathConstants class
If you want complete list you can specify like this
<
 If the xml is present as string we can use StringReader to create InputSource
StringReader converts String to Stream of character
Common Error : when we use Xpath again with the same InputResource , it will throw Exception with message like this
javax.xml.xpath.XPathExpressionException at org.apache.xpath.jaxp.XPathImpl.evaluate(XPathImpl.java:481) 
java.io.IOException: Stream Closed 
once the Xpath expression is evaluated on particular InputSource , it's stream is closed We have to use new InputSource with new InputStream for every Xpath evaluation .