Home » Core Java » xml » XPath » Xpath Find by Attribute Value Example

About Mohammad Meraj Zia

Mohammad Meraj Zia
I did my Engineering in Information Technology from IET, Lucknow, India. Currently doing MSc in Information Technology from Derby University. I have worked in Java/J2EE domain for the last 10 years. Have good understanding of Payment and Finance domains.

Xpath Find by Attribute Value Example

In this article we will learn how to find an xml element using attribute value. We will use IDEA IntelliJ 14.0.2 and Java 8.

1. Introduction

XPath is a W3C recommendation. XPath can be used to navigate through elements and attributes in an XML document. XPath is a syntax for defining parts of an XML document. XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system. XPath expressions can be used in JavaScript, Java, XML Schema, PHP, Python, C and C++, and lots of other languages. XPath contains a library of standard functions.

In XPath, there are seven kinds of nodes: element, attribute, text, namespace, processing-instruction, comment, and document nodes. XML documents are treated as trees of nodes. The topmost element of the tree is called the root element. Atomic values are nodes with no children or parent.

2. Find by Attribute Value

2.1 Create a project

In this section we will see how to create a Java project in IDEA IntelliJ.

Click on File => New. In the New Project Window choose Java:

Figure 1. Create New Java Project

On the next window leave everything default and click ‘Next’. Enter the Project name and location and click Finish

Figure 2. Java Project Details

IntelliJ will create the project structure as below:

Figure 3. Project Structure

2.2 Create new class

In this section we will see how to create a new java class. First we will see how to create a new package. Right click on the src folder and choose New => Package:

Figure 4. Create New Package

On the next pop-up window enter the package name and click OK. IntelliJ will create the new package.

Figure 5. Package Name.

To create a new class right click on the package and choose New => Java Class and click OK. IntelliJ will create a new java class in the given package.

Figure 6. Java 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.

XPathSearchByAttributeValue.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 17/04/2017.
*/
public class XPathSearchByAttributeValue {
  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 attribute value. 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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz