HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java XML / Java XPath Get Attribute Value from XML

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.io.IOException;
import java.io.StringReader;
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
{
	@SuppressWarnings("unchecked")
	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>" +
												</users>")));

		//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++)
        {
        	System.out.println((userIds.get(i)).getAttributeValue("id").trim());
        }
	}
}

Program output.

13423
32424
543534
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
at com.sun.org.apache.xpath.internal.jaxp.XPathExpressionImpl.eval(XPathExpressionImpl.java:116)
at com.sun.org.apache.xpath.internal.jaxp.XPathExpressionImpl.eval(XPathExpressionImpl.java:98)
at com.sun.org.apache.xpath.internal.jaxp.XPathExpressionImpl.evaluate(XPathExpressionImpl.java:180)

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Srinivasan.S

    August 3, 2016

    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.

    <outcome>
    <item>
    <Block>
    <div class="h1">
    <p>Read directions.</p>
    <span>
    <obj>
    <div class="h2">
    <div class="h3"/>
    <div class="h4">
    <p class="h5">
    Read directions.
    </p>
    </div>
    </div>
    </obj>
    </span>
    </div>
    <graphic>
    <crome>
    <p>Jill table</p>
    </prompt>
    <obj>
    <p>NONE</p>
    </obj>
    <Img>
    <obj>
    <p>NONE</p>
    </obj>
    </Img>
    <Img>
    <obj>
    <p>NONE</p>
    </obj>
    </gapImg>
    <target>
    </graphic>
    </itemBody>
    </outcome>
    
    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++) {
    					    System.out.println(nodes.item(i).getNodeValue());
    					}
    					
    				}
    		catch (XPathExpressionException e) {
    			e.printStackTrace();
    			}
    	  	}	
    
  2. rjoshir

    December 18, 2012

    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(Class.java:186) at org.jdom.xpath.XPath.newInstance(XPath.java:134) at xmlattributes.Main.main(Main.java:61)

    pl guide me me added jdom1.2.2 jar

    Rajendra

    • Lokesh Gupta

      December 18, 2012

      Rajendra, please make sure to add both jars i.r. jdom and jaxen in your class path.

      Download from below locations:

      https://mvnrepository.com/artifact/org.jdom
      http://www.java2s.com/Code/Jar/j/Downloadjaxen111jar.htm

Comments are closed on this article!

Search Tutorials

Java XML Tutorial

  • Java – Read XML DOM Parser
  • Java – Read XML SAX Parser
  • Java – Read XML JDOM2 Parser
  • Java – Read XML StAX Parser
  • Java – DOM vs SAX Parser
  • Java – Convert XML to Properties
  • Java – Convert Properties to XML
  • Java – Convert String to XML
  • Java – Convert XML to String
  • Java – XPath Tutorial
  • Java – Evaluate XPath on DOM
  • Java – Evaluate XPath on String
  • Java – XPath Examples
  • Java – XPath NamespaceContext
  • Java – Get Attribute using XPath
  • Java – XPath Attribute Examples
  • Java – Check if XML tag exists?

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces