How to use XPATH in JAVA (simple example)


In this post, I will show you how to parse a XML document by using XPath technology on the Java Platform.

Here is the XML sample for using as a content for parsing operations;

books.xml file content;

<?xml version="1.0" encoding="UTF-8"?>
<LIBRARY>
    <BOOKS>
        <BOOK isbn="ABCD7327923">
            <NAME>Java Programing</NAME>
            <SUBJECT>Java J2EE</SUBJECT>
            <AUTHORS>
                <AUTHOR>Tuna TORE</AUTHOR>
                <AUTHOR>Linus Torvalds</AUTHOR>
                <AUTHOR>James Gosling</AUTHOR>
            </AUTHORS>
        </BOOK>
        <BOOK isbn="DFGH09093232">
             <NAME>XPATH for Dummies</NAME>
           <SUBJECT> XPATH development</SUBJECT>
            <AUTHORS>
                <AUTHOR>Linus Torvalds</AUTHOR>
                <AUTHOR>John Hawking</AUTHOR>
            </AUTHORS>
        </BOOK>
        <BOOK isbn="DSKL2393A">
            <NAME>J2EE Patterns</NAME>
            <SUBJECT>Design Patterns</SUBJECT>
            <AUTHORS>
                <AUTHOR>Aka Tuna</AUTHOR>
            </AUTHORS>
        </BOOK>
    </BOOKS>
    <DVDS>
        <DVD id="123456">
            <NAME>Music DVD</NAME>
            <CONTENT>Music</CONTENT>
            <AUTHORS>
                <AUTHOR>James Gosling</AUTHOR>
                <AUTHOR>Bill Gates</AUTHOR>
            </AUTHORS>
        </DVD>
        <DVD id="3213324">
            <NAME>Natural Science</NAME>
            <CONTENT>Science</CONTENT>
            <AUTHORS>
                <AUTHOR>John Green</AUTHOR>
                <AUTHOR>Bill Gates</AUTHOR>
            </AUTHORS>
        </DVD>
        <DVD id="4353534">
            <NAME>Rally</NAME>
            <CONTENT>Race</CONTENT>
            <AUTHORS>
                <AUTHOR>Tuna</AUTHOR>
            </AUTHORS>
        </DVD>
    </DVDS>
</LIBRARY>

Main.java class

package xpathexample;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

/**
*
* @author tunatore
*/
public class Main {

public static void main(String[] args) throws Exception {

//loading the XML document from a file
DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
builderfactory.setNamespaceAware(true);

DocumentBuilder builder = builderfactory.newDocumentBuilder();
Document xmlDocument = builder.parse(
new File(Main.class.getResource("books.xml").getFile().replace("%20", " ")));

XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
XPath xPath = factory.newXPath();

//getting the name of the book having an isbn number == ABCD7327923
String isbnNum = "ABCD7327923";
XPathExpression xPathExpression = xPath.compile("//LIBRARY//BOOKS//BOOK[@isbn='" +isbnNum + "']//NAME");
String nameOfTheBook = xPathExpression.evaluate(xmlDocument,XPathConstants.STRING).toString();

System.out.println("name of the Book ---> " + nameOfTheBook);

//getting all authors for the book having an isbn number == ABCD7327923
xPathExpression = xPath.compile("//LIBRARY//BOOKS//BOOK[@isbn='" +isbnNum + "']//AUTHORS//AUTHOR");

NodeList nodeListBook =  (NodeList) xPathExpression.evaluate(xmlDocument,XPathConstants.NODESET);
System.out.println("Total number of authors for the book " + nameOfTheBook + " is --> " + nodeListBook.getLength());

for (int index = 0; index < nodeListBook.getLength(); index++) {
String author = nodeListBook.item(index).getTextContent();
System.out.println("Author " + (index + 1) + " ---> " + author);
}

//getting all tags for the dvd having id == 3213324
String dvdID = "3213324";
xPathExpression = xPath.compile("//LIBRARY//DVDS//DVD[@id='" +dvdID + "']");
NodeList nodeDVD =  (NodeList) xPathExpression.evaluate(xmlDocument,XPathConstants.NODESET);
NodeList nodeListForDVD = nodeDVD.item(0).getChildNodes();

for (int index = 0; index < nodeDVD.item(0).getChildNodes().getLength(); index++) {
String tagName = nodeListForDVD.item(index).getNodeName();
String tagValue = nodeListForDVD.item(index).getTextContent();
if(!tagName.equals("#text")) //handling empty comment (#text)
System.out.println(tagName + " value ---> " + tagValue);
}
}
}

The output of the program;

run:
name of the Book —> Java Programing
Total number of authors for the book Java Programing is –> 3
Author 1 —> Tuna TORE
Author 2 —> Linus Torvalds
Author 3 —> James Gosling
NAME value —> Natural Science
CONTENT value —> Science
AUTHORS value —>
John Green
Bill Gates

BUILD SUCCESSFUL (total time: 2 seconds)

Download Source

Advertisements

2 thoughts on “How to use XPATH in JAVA (simple example)

  1. Seems like you truly understand quite a lot pertaining
    to this topic and it exhibits with this specific article, titled “How to use XPATH in JAVA (simple example) Tuna Töre”.

    I am grateful -John

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s