EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials XML Tutorial XPath Expressions
 

XPath Expressions

Priya Pedamkar
Article byPriya Pedamkar

Updated July 6, 2023

XPath-Expressions

 

 

Introduction to XPath Expressions

XPath expression is defined as a simple line of code that gives useful information from the hierarchical XML Document. It describes any attribute or Location of any type of information that was put in, and every part of XPath is treated as an expression (a character String). An Xpath Engine takes an Xpath Expression as Strings. It also does some arithmetic operations and checks for any conditions in the data. To select considerable data, Xpath has a library standard function. Xpath is used in a lot of languages like Java, PHP, Python, etc.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

List of XPath Expressions

Some frequent use of Xpath Expressions is listed below:

Elements: And some Xpath functions help in searching various data fragments inside the XML Document.

Sr. No Xpath Expression Path Name / Description
1. Name Node name
2 / This element gets all the Context node
3 // This tracks the nodes anywhere in the XML Document or simply a Descendants.
4 * It specifies all the elements in the Document which are a child of the context node.
5 | This relates to the OR Operator, which combines either the first or second expression.
6 . This selects the current node
7 ../ It refers to the parent context node
8 @attr Refers an attribute
9 @attr = ‘value ‘ Retrieves the Attribute value of an element.
10 Position() It returns the current position of an element for the other child element.
11 Last() It specifies the number of nodes within the specified context.

Example

Now let us look at some examples on Xpath Expressions to see how they work with the above-listed types. The Xpath expressions that are not in the node sets cannot be embedded in an XSL:template element.

ordr.xml

<?xml version="1.0" standalone="yes"?>
<Orderinfo>
<Customer id="01">
<cname>Jay Katrine</cname>
<destination Country ="India" Delivdate=" 5 days">No Shipping Charge</destination>
<email>[email protected]</email>
</Customer>
<Customer id="02">
<cname from="xxx">Roy maccline</cname>
<destination Country ="USA" Delivdate=" 10 days">Shipping Charge</destination>
<email>[email protected]</email>
</Customer>
<Customer id="03">
<cname>Rosy Diana</cname>
<destination Country ="Singapore" Delivdate=" 7 days">Shipping Charge</destination>
<email>[email protected]</email>
</Customer>
</Orderinfo>

For the above XML document, the Xpath is evaluated as:

Sr. NO Xpath Access Explanation
1 Orderinfo Root_element name, which has child elements.This Select Orderinfo element with all child nodes.
2 Orderinfo/Customer This is a child of a child element. This returns the Customer node of the Orderinfo element
3 Orderinfo/Customer/cname Descendants of a child of the child element node. This goes as Selecting the name element of Customer, which is again an element of Orderinfo element.
4 */Customer This selects all the ancestral elements. Selects all Customer ancestor parent elements.
5 Orderinfo//Customer  It gives all the Customer elements of the Orderinfo element.
6 Customer[@id=”01”] It selects the child element with the attribute id = “1”.
7 //Orderinfo. Customer [ cname=” Jay Katrine” | cname=” Rosy Diana] This return either one of the cname values

The Xpath is written properly by using the concept of parent-child relationships in an expression.

Examples to Implement of Xpath Expressions using Java Library

Let’s see an example with an XML document through which different parts of an XML are retrieved using Xpath using Java XML Parsers. The below Java Xpath successfully runs in JDK. To create an XPath expression, java specifies factory methods that are defined in the code.

expr.xml

<?xml version="1.0" standalone="yes"?>
<Orderinfo>
<Customer id="01">
<cname>Jay Katrine</cname>
<destination Country ="India" Delivdate=" 5 days">No Shipping Charge</destination>
<email>[email protected]</email>
</Customer>
<Customer id="02">
<cname from="xxx">Roy maccline</cname>
<destination Country ="USA" Delivdate=" 10 days">Shipping Charge</destination>
<email>[email protected]</email>
</Customer>
<Customer id="03">
<cname>Rosy Diana</cname>
<destination Country ="Singapore" Delivdate=" 7 days">Shipping Charge</destination>
<email>[email protected]</email>
</Customer>
</Orderinfo>

The corresponding Java File for Xpath is

Expr.java

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.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Expr
{
public static void main(String[] args) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("expr.xml");
// Creating an Xpath to access the node
XPathFactory xpathfactory = XPathFactory.newInstance();
XPath xpath = xpathfactory.newXPath();
System.out.println(" 1. Get the Customer Name with thier Order Id");
XPathExpression ex = xpath.compile("//Customer[@id=02]/cname/text()");
Object res = ex.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) res;
for (int j = 0; j < nodes.getLength(); j++) {
System.out.println(nodes.item(j).getNodeValue());
}
System.out.println("2. Get the Customer Name with their Order Id");
ex = xpath.compile("//Customer[@id=03]/cname//text()");
res = ex.evaluate(doc, XPathConstants.NODESET);
nodes = (NodeList) res;
for (int j = 0; j < nodes.getLength(); j++) {
System.out.println(nodes.item(j).getNodeValue());
}
}
}

In the below program output, the dom uses objects in retrieving a particular node. In this case, it searches for the Order ID of the element Customer.

Output:

XPath Expressions - 1

Example #2

Code:

import java.util.ArrayList;
import java.util.List;
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 XPathdemo
{
public static void main(String[] args) throws Exception
{
String fileName= "expr.xml";
Document document = getDocument(fileName);
String xpathExpression = "";
// ALL Customer ids in the doc
xpathExpression = "/Orderinfo/Customer/@id";
System.out.println( evaluateXPath(document, xpathExpression) );
//Retrieving Customer ids with the Destination element
xpathExpression = "/Orderinfo/Customer[destination/Country='USA']/@id";
System.out.println( evaluateXPath(document, xpathExpression) );
//Displaying customer id of 'Rosy' [particular content] xpathExpression = "/Orderinfo/Customer[cname='Rosy Diana']/@id";
System.out.println( evaluateXPath(document, xpathExpression) );
//Displaying customer ids greater than or equal to 2.
xpathExpression = "/Orderinfo/Customer/@id[. >= 02]";
System.out.println( evaluateXPath(document, xpathExpression) );
//Displaying customer whose id contains the value '03'
xpathExpression = "/Orderinfo/Customer[contains(@id,'03')]/cname/text()";
System.out.println( evaluateXPath(document, xpathExpression) );
}
private static List<String> evaluateXPath(Document document, String xpathExpression) throws Exception
{
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xp = xpathFactory.newXPath();
List<String> values = new ArrayList<>();
try
{
XPathExpression exp = xp.compile(xpathExpression);
NodeList nodes = (NodeList) exp.evaluate(document, XPathConstants.NODESET);
for (int k = 0; k < nodes.getLength(); k++) {
values.add(nodes.item(k).getNodeValue());
}
} catch (XPathExpressionException e1) {
e1.printStackTrace();
}
return values;
}
private static Document getDocument(String fileName) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document d = builder.parse(fileName);
return d;
}
}

Output:

XPath Expressions - 2

Note: Using XSL, we can examine the function position () and last (). Also, The Xpath Expression can be evaluated to test the program code before making them structured.

Conclusion

Therefore, we have seen a Quick round-up on Xpath Expressions, where looks just like a file system path. The result produced by the Expression is either in the form of a node set or a String. As it helps select node sets, they contain the complete path of the element from the root. The added advantage is by taking high performance with the component inside.

Recommended Articles

This is a guide to XPath Expressions. Here we discuss the frequent use of Xpath Expressions, with programming examples for better understanding. You can also go through our other related articles to learn more –

  1. XPath Operators
  2. JSTL Tags
  3. XQuery
  4. What is XPath?

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW