Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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 a considerable data Xpath has a library standard function. Xpath is used in a lot of languages like Java, PHP, Python, etc.

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 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




Jay Katrine
No Shipping Charge
[email protected]


Roy maccline
Shipping Charge
[email protected]


Rosy Diana
Shipping Charge
[email protected]

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 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 which are defined in the code.

expr.xml




Jay Katrine
No Shipping Charge
[email protected]


Roy maccline
Shipping Charge
[email protected]


Rosy Diana
Shipping Charge
[email protected]

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 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 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:

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 evaluateXPath(Document document, String xpathExpression) throws Exception
{
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xp = xpathFactory.newXPath();
List values = new ArrayList();
try
{
XPathExpression exp = xp.compile(xpathExpression);
NodeList nodes = (NodeList) exp.evaluate(document, XPathConstants.NODESET);
for (int k = 0; 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:

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 it looks just like a file system path. The result produced by the Expression is either in the form of node-set or 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 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?

The post XPath Expressions appeared first on EDUCBA.



This post first appeared on Free Online CFA Calculator Training Course | EduCB, please read the originial post: here

Share the post

XPath Expressions

×

Subscribe to Free Online Cfa Calculator Training Course | Educb

Get updates delivered right to your inbox!

Thank you for your subscription

×