Friday, 15 February 2013

Tutorial On How to Use Xpath on xml file or string in Java

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
 
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
Create an InputSource instance from InputStream of xml file .
InputSource inputSource = new InputSource(stream);

now get the desired value by entering xpath expresion like this
You can specify required constants from XPathConstants class
String value = (String) xpath.evaluate("/auction/bids/bid[1]/price", inputSource,XPathConstants.STRING);

If you want complete list you can specify like this
NodeList list  = (NodeList) xpath.evaluate(expression, source,XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++)
{
value = nodes.item(i).getTextContent();
}


 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 .