Friday, April 3, 2009

XPATH Java simple example

XPath is used to search any node any element in XML file. ---- very basic defination.

XPath is a fourth generation declarative language for locating nodes in XML documents. This is much more robust than writing the detailed search and navigation code yourself using DOM, SAX, or JDOM. using XPath in a Java program is like using SQL in a Java program. To extract information from a database, you write a SQL statement indicating what information you want and you ask JDBC to fetch it for you. You neither know nor care how JDBC communicates with the database. Similarly with XML, you write an XPath expression indicating what information you want from an XML document and ask the XPath engine to fetch it, without concerning yourself with the exact algorithms used to search the XML document.

1. Suppose I have persons.xml
<?xml version="1.0" ?>
<information>
<person id="1">
<name>Binod</name>
<age>24</age>
<gender>Male</gender>
</person>

<person id="2">
<name>Pramod</name>
<age>22</age>
<gender>Male</gender>
</person>

<person id="3">
<name>Swetha</name>
<age>19</age>
<gender>Female</gender>
</person>
</information>

2. XPathJavaExample.java

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XPathJavaExample {
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("persons.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//person/*/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
}

The output of this xpath query ("//person/*/text()");
Binod
24
Male
Pramod
22
Male
Swetha
19
Female

XPathExpression expr = xpath.compile("//person[last()]/*/text()"); This will be give the last record
Swetha
19
Female

XPathExpression expr = xpath.compile("//person/name/text()"); Here name is mentioned instaed of *. * means all the attribute. The output
Binod
Pramod
Swetha
Only name shows here.

XPathExpression expr = xpath.compile("//person[1]/*/text()"); Retrive first record
Binod
24
Male

XPathExpression expr = xpath.compile("//name/text()"); It will show all the name tag, that would be anywhere in xml. The output
Binod
Pramod
Swetha

XPathExpression expr = xpath.compile("//person[age>20]/*/text()"); Output would be
all age that is greater than 20
Binod
24
Male
Pramod
22
Male


There are numbers of xpath expression. You can get from google. Here I showed only few of them. But it is easy to understand .......... :)

9 comments:

  1. Good blog...very simple. Rohan

    ReplyDelete
  2. Undoubtlly very simple. Greate job.

    ReplyDelete
  3. Hi Binod,

    Firstly, thanks for this post.

    I have a question: Do you know how to extract attribute values using XPath?

    Check this Element:



    I need Tue, 24, 9, 17, Cloudy, and 26.

    I appreciate any help.

    So long.

    ReplyDelete
  4. hi it was very usefull thanks but how to find Swetha's record

    i mean all records which name is Swetha and expression

    ReplyDelete
  5. http://www.roseindia.net/tutorials/xPath/java-xpath.shtml

    ReplyDelete
  6. very simple explanation good.

    ReplyDelete
  7. Its like you read my mind! You seem to know so much about this,
    like you wrote the book in it or something. I think that you could do with a few pics to drive
    the message home a bit, but other than that, this is wonderful blog.
    A fantastic read. I will certainly be back.
    Also see my webpage - site here

    ReplyDelete

You can put your comments here (Either feedback or your Question related to blog)