HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java XML / Java 8 xpath example – Evaluate xpath on string

Java 8 xpath example – Evaluate xpath on string

Java example to evaluate xpath on string and return result XML in string itself.

1. XPath example – Evaluate xpath on xml string

  1. Create org.xml.sax.InputSource containing with StringReader referencing to XML string.
  2. Create XPath from XPathFactory.
  3. Use xpath.evaluate('expression', inputSource) to get result HTML.
package com.howtodoinjava.demo;

import java.io.StringReader;

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.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

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

		String xml = "<employees>"
					+ "<employee id=\"1\">"
						+ "<firstName>Lokesh</firstName>"
						+ "<lastName>Gupta</lastName>"
						+ "<department><id>101</id><name>IT</name></department>"
					+ "</employee>"
				   + "</employees>";
		
		InputSource inputXML = new InputSource( new StringReader( xml ) );
		
        XPath xPath = XPathFactory.newInstance().newXPath();
        
        String result = xPath.evaluate("/employees/employee/firstName", inputXML);

        System.out.println(result);
    }
}    

Program output:

Lokesh

2. XPath example – Evaluate xpath on xml file

package com.howtodoinjava.demo;

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.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

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

		String xmlFile = "employees.xml";
		
		//Get DOM
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document xml = db.parse(xmlFile);

        //Get XPath 
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        
        //Get first match
        String name = (String) xpath.evaluate("/employees/employee/firstName", xml, XPathConstants.STRING);
        
        System.out.println(name);	//Lokesh
        
        //Get all matches
        NodeList nodes = (NodeList) xpath.evaluate("/employees/employee/@id", xml, XPathConstants.NODESET);
        
        for (int i = 0; i < nodes.getLength(); i++) {
        	System.out.println(nodes.item(i).getNodeValue());	//1 2
        }
    }
}    

Program output:

Lokesh
1
2

The input xml file is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees>
    <employee id="1">
        <firstName>Lokesh</firstName>
        <lastName>Gupta</lastName>
        <department>
            <id>101</id>
            <name>IT</name>
        </department>
    </employee>
    <employee id="2">
        <firstName>Brian</firstName>
        <lastName>Schultz</lastName>
        <department>
            <id>102</id>
            <name>HR</name>
        </department>
    </employee>
</employees>

In above Xpath tutorial, we learned to evaluate xpath on string with example.

Happy Learning !!

Read More:

Java xpath example from file
Java xpath tutorial
How to get attribute value in xml using xpath in java

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.

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