Java XPath Get Attribute Value from XML

Many times we need to parse an XML file and extract information from it. For example, read attribute value of an XML element with xpath. In this Java XPath tutorial, learn to get attribute value from an XML String.

I am using jdom and jaxen. These are other plenty open source APIs available also, but the idea remains the same.

Java program to get value from in Java using XPath

Below given Java program create a DOM object from supplied XML string. It then applies the XPATH expression using XPath.selectNodes() method.

Method returns list of Element instances which are result of evaluating XPath expression. You can iterate the list and use the results.

package com.howtodoinjava.xml;

import java.util.ArrayList;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

public class XmlAttributesUsingXPathExample
	public static void main(String[] args) throws JDOMException, IOException
		Document doc = new SAXBuilder(false).build(new StringReader(new String(
                                               <users>	" +
													<user id='13423'>" +
														<firstname>Andre</firstname>" +
													</user>" +
													<user id='32424'>" +
														<firstname>Peter</firstname>" +
													</user> " +
													<user id='543534'>" +
														<firstname>Sandra</firstname>" +
													</user>" +

		//Build the xpath expression
		XPath xpathExpression = XPath.newInstance("//*[@id]");

		//Apply xpath and fetch all matching nodes
		ArrayList<Element> userIds =  (ArrayList<Element>) xpathExpression.selectNodes(doc);

		//Iterate over naodes and print the value
		for (int i = 0; i < userIds.size(); i++)

Program output.

Please include correct class files. Invalid imports can cause in following error or something like this.

java.lang.ClassCastException: org.jdom.Document cannot be cast to org.w3c.dom.Node

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

3 thoughts on “Java XPath Get Attribute Value from XML”

  1. I need to check child tag contain text() using xPath. I have one parent tag it have more child and Sub child. I need to check any of my child tag contain text(). If it may ,, or any customize tag too. and I nee to print it nodeName.

    <div class="h1">
    <p>Read directions.</p>
    <div class="h2">
    <div class="h3"/>
    <div class="h4">
    <p class="h5">
    Read directions.
    <p>Jill table</p>
    private static void addAttributeId(Node someNode, Document doc) {
    		  XPath xPath = XPathFactory.newInstance().newXPath();
    	       // NodeList nodesName;
    				try {
    					XPathExpression expr =  xPath.compile("//itemBody/text()");
    					Object result = expr.evaluate(doc, XPathConstants.NODESET);
    					NodeList nodes = (NodeList) result;
    					for (int i = 0; i < nodes.getLength(); i++) {
    		catch (XPathExpressionException e) {
  2. I am getting following exception at

    XPath xpathExpression = XPath.newInstance(“//*[@id]”);

    Exception in thread “main” java.lang.NoClassDefFoundError: org/jaxen/JaxenException at java.lang.Class.forName0(Native Method) at java.lang.Class.forName( at org.jdom.xpath.XPath.newInstance( at xmlattributes.Main.main(

    pl guide me me added jdom1.2.2 jar



Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.