XPath

Xpath Search by id Example

In this article we will learn how to search for an element (by id) in an XML using XPath. We will make use of IDEA IntelliJ to work on this. I am using IntelliJ 14.0.2 and Java 8.

1. Introduction

XPath is a W3C recommendation. XPath stands for XML Path Language. XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the path expressions you use with traditional computer file systems. XPath contains over 200 built-in functions. XPath is a major element in the XSLT standard. XPath includes over 200 built-in functions. There are functions for string values, numeric values, booleans, date and time comparison, node manipulation, sequence manipulation, and much more. Today XPath expressions can also be used in JavaScript, Java, XML Schema, PHP, Python, C and C++, and lots of other languages.

2. Search by Id

In this section we will see how to search an xml element using id. First we will discuss how to create a project using IntelliJ. Then we will write the code for it.

2.1 Creating project in IntelliJ

Open IntelliJ and click on File => New Project… In the New Project window choose Java.

Figure 1. New Java Project

Click Next. On the next window click Next. Give the Project name and the location of the project. and click Finish.

Figure 2. Project Details

IntelliJ will create the default structure of the project as below:

Figure 3. Project Structure

2.2 Create New Class

In this section we will learn how to create a new java class in IntelliJ. First we are going to create a new package. Right click on the ‘src’ folder and choose New => Package.

Figure 4. Create New Java Package

In the pop-up enter the new package name and click OK. IntelliJ will create the given package in the ‘src’ folder.

Figure 5. Package Name

Now right click on the package and choose New => Java Class. Enter the class name and click OK.

Figure 6. Create New Class

2.3. Code

In this section we will start coding for the example. Create a new XML file in the same directory where you java class is. You can create the XML at some other place as well and give the relevant path but for simplicity purpose we will create the XML in the same directory. To create the xml file right click on the package which you just created and choose New => File. Enter the file name and click OK.

The XML which we are going to use for this example looks as below:

test.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Persons>
  <person id="345623">
    <fullName>Steve Jones</fullName>
    <address>43 North wing, Washington</address>
    <dateOfBirth>21 March 2001</dateOfBirth>
  </person>
  <person id="972376">
    <fullName>Sachin Tendulkar</fullName>
    <address>3 Pahaar gang, Bombay</address>
    <dateOfBirth>21 March 1982</dateOfBirth>
  </person>
</Persons>

Now we will write a simple java code to find an element in this xml using the attribute (id). First we will show you the full java code then we will explain what is going on in the code.

XPathSearchById.java

package com.javacodegeeks;

import org.w3c.dom.Node;
import org.xml.sax.InputSource;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

/**
* Created by Meraj on 14/04/2017.
*/
public class XPathSearchById {

  public static void main(String[] args) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    String expression = "/Persons/person[@id=972376]/fullName";
    InputSource inputSource = new InputSource("src//com//javacodegeeks//test.xml");
    try {
      Node node = (Node) xpath.evaluate(expression, inputSource, XPathConstants.NODE);
      System.out.println(node.getTextContent());
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }
  }
}

We first create the javax.xml.xpath.XPath instance using the javax.xml.xpath.XPathFactory by calling the newInstance() method of the factory class. Then we define the XPath expression where we use the @id attribute to find the person node with the give id attribute. Then we define the input source by passing the location of our xml file. This class allows a SAX application to encapsulate information about an input source in a single object, which may include a public identifier, a system identifier, a byte stream (possibly with a specified encoding), and/or a character stream.
Then we will call the xpath.evaluate() to evaluate an XPath expression in the context of the specified InputSource and return the result as the specified type.

3. Conclusion

In this article we learned about XPath and also how to search an element using the id. We discussed how to create a simple  java project in IntelliJ and how how to write a simple program to find the element in an xml using XPath.

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button