Updated April 5, 2023
Definition of XPath Descendant
Xpath Descendant is defined as a context node that is represented by the descendant axis; a descendant is a child node, a child of a child, and so on; consequently, the descendant axis doesn’t contain attribute or namespace nodes.XPath is a mini-language that describes a node pattern to select a set of nodes. Descendant is declared as ‘ // ‘ so a child can be defined as a// b, to go deeper into the XML tree descendant gives away.
Syntax:
The general Syntax of XPath Descendant is given as
//node[attribute='value']//descendant::attribute
How XPath Descendant Works?
Identifies and returns all of the current element’s element descendants, which involves traversing down under the current element’s node. Though XPath has both absolute and Relative expression with them sometimes it may be a time-consuming process if we want to select a child element. The “// “ makes the job easier while selecting every element that has a particular element as an ancestor. In Below XPath, we could see all the <li> elements under the parent node are displayed.
<div class =”hh”>
<div class=”hhrow” style=”bottom: 1px;”>
<ul id=”ma” class=”hhma”>
<li id =”jjj1” class=”hhhb”/>
<li id =”jjj2” class=”hhhc”/>
<li id =”jjj3” class=”hhhd”/>
<li id =”jjj4” class=”hhhf”/>
<li id =”jjj5” class=”hhhj”/>
</ul>
lets take a quick tour on the nodes to see a current node.
<div class=”dou” style=””>
<p>
< input name….>
<user name class=”fine”>
</p>
<p>
<input type=”text” id=”eee0”>
</p>
The Xpath using Descendant axis is given as
//div[@class =’dou’] //descendant:: input(1 of 2)
The above Xpath expression identifies two elements .here div is the current element. we can select this node using descendant or self-axis.
//div[@class =’dou’] //descendant
The above statement identifies one node. If the expression is changed from div to input then we can get the subsequent child nodes.
The descendant axis is similar to the child axis, but the main distinction is that the descendant only shows the children and sub-children of the same node.
Few Descendants axis:
descendant::a | Select all hyperlinks below the current node. |
/descendant::table | Select all tables in the file |
child::section/descendant::image | Select images in a given part |
.[descendant::image] | Selects the current node if it has an image. |
Next, we shall take an input like
<System>
<AA id="11"/>
<AA id="22"/>
<BB id="33">
<AA id="33-11"/>
<BB id="33-12"/>
<AA id="33-30"/>
</BB>
<AA id="40"/>
<BB id="50"/>
<CC id="60"/>
<AA id="70"/>
<BB id="80"/>
<CC id="90"/></System>
So here System is the Context node, thus selection of an element by the user are performed relative to this.
- To select all descendants named ‘AA’.
/System/Descendant::AA
It gives the result as
<AA id="11"/>
<AA id="12"/>
<AA id="33-11"/>
<AA id="33-33"/>
<AA id="40"/>
<AA id="70"/><AA id="80"/>
Examples of XPath Descendant
Let’s look at an XML document whose descendant axis nodes are retrieved by Java XML Parsers utilizing an Xpath expression. The Java Xpath below was successfully executed in Jdk. Java defines factory methods that are created in the code to create an XPath expression.
Example #1
expr.xml
<?xml version="1.0" standalone="yes"?>
<bookinginfo>
<passenger id="01">
<pname>Rose Marquarette</pname>
<destination Country ="Singapore" Arrival=" 7 days">GST Tax</destination>
<email>[email protected]</email>
</passenger >
<passenger id="02">
<pname from="India">Roy Vincy</pname>
<destination Country ="Sweden" Delivdate=" 10 days">Shipping Charge</destination>
<email>[email protected]</email>
</passenger>
<passenger id="08">
<pname>Tom donald</pname>
<destination Country ="NewZaland" Arrival=" 8 days">No Tax</destination>
<email>[email protected]</email>
</passenger >
</bookinginfo>
Airline.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 Airline
{
public static void main(String[] args) throws Exception
{
DocumentBuilderFactory fa= DocumentBuilderFactory.newInstance();
fa.setNamespaceAware(true);
DocumentBuilder builder = fa.newDocumentBuilder();
Document d = builder.parse("expr.xml");
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
System.out.println(" 1. Display Booking Name with thier Order Id");
XPathExpression ex1 = xp.compile("//passenger[@id=02]/destination/text()");
Object res = ex1.evaluate(d, 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. Display Booking Name with their Order Id");
ex1 = xp.compile("//passenger[@id=08]/pname//text()");
res = ex1.evaluate(d, XPathConstants.NODESET);
nodes = (NodeList) res;
for (int j = 0; j < nodes.getLength(); j++) {
System.out.println(nodes.item(j).getNodeValue());
}
}
}
Explanation: The above code takes a class Airline and we parse this using Java XML by loading the DOM document object, Next, we should place an XML file in the current working directory. An Xpath object is done by an Xpath factory.Next an expression “//descendant:: passenger /text() displays the order id text. Here is the output:
Output:
Example #2
parties.xml
<?xml version="1.0" ?>
<Parties>
<Democractic id="01">
<Dname>XXXXX</Dname>
<Dage>45</Dage>
<State>California</State>
</Democractic>
<Democractic id="10">
<Dname>AAAAA</Dname>
<Dage>52</Dage>
<State>Arizona</State>
</Democractic>
<Democractic id="05">
<Dname>KKKKK</Dname>
<Dage>60</Dage>
<State>Seattle</State>
</Democractic>
</Parties>
Desc.java
import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;
public class Desc {
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domF =
DocumentBuilderFactory.newInstance();
domF.setNamespaceAware(true);
DocumentBuilder bu = domF.newDocumentBuilder();
Document doct = bu.parse("parties.xml");
XPath xp = XPathFactory.newInstance().newXPath();
XPathExpression ex = xp.compile("/Parties/descendant::*");
Object res = ex.evaluate(doct, XPathConstants.NODESET);
NodeList nodes = (NodeList) res;
for (int k = 0; k < nodes.getLength(); k++) {
System.out.println(nodes.item(k).getNodeName());
}
ex = xp.compile("//descendant::Democractic/*/text()");
res = ex.evaluate(doct, XPathConstants.NODESET);
nodes = (NodeList) res;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.print(nodes.item(i).getNodeValue()+", ");
}
}
}
Explanation: Using Descendant:: Democratic names the value is displayed as given below.
Output:
Example #3:Descendant- Axes
In the below code it shows the output matching the ancestors’ grade for the child elements first name, last name. Therefore, the other values like grade or stud are invisible in the result.
Std.xml
<?xml version = "1.0" encoding="utf-8"?>
<grade>
<stud id = "545">
<finame>nivas</finame>
<laname>raksh</laname>
<scorepoint>82</scorepoint>
</stud>
<stud id = "622">
<finame>britian dou</finame>
<laname>wasles tom</laname>
<scorepoint>91</scorepoint>
</stud>
<stud id= "354">
<finame>Ales river</finame>
<laname>Stefen</laname>
<scorepoint>84</scorepoint>
</stud>
</grade>
Explanation: The Referenced screenshot of the code is given below.
Though XPath has several solutions to retrieve an element from the document, We need to find the best trick to get the task easier by seeking the correct approach.
Conclusion
Therefore we conclude this article by applying the XPath elements to identify the objects in any automation of websites. We have gone through the Descendant axes on the context part which itself is an ancestor. The Xpath axes are very important in any organization and therefore this article covered all important syntax and implementation using java with suitable examples.
Recommended Articles
This is a guide to XPath Descendant. Here we discuss the introduction and how XPath descendant works? along with different examples and its code implementation. You may also have a look at the following articles to learn more –