Updated April 4, 2023
Definition of XPath parent
In XPath, the parent node of the current node selected in the web page is retrieved using the Parent method. It comes in handy when we choose an element and need to utilise Xpath to fetch the parent element. This method can also be used to find out who the parent’s parents are and abbreviated as (..). XPath parent is one of the methods of Xpath Axes. XPath axes aid in the discovery of elements in an XML document based on their relationships with other components.
Syntax
The following is the syntax for the parent’s axis and the XPath expression will be given as:
/parent::tagName
How does XPath parent work?
Axes in XPath are techniques for identifying dynamic elements that are impossible to detect using standard XPath methods such as class. Axes are named after the axis on which elements are arranged relative to one another. Each element and attribute has a single parent. As a result, the parent axis is empty when the current node is the root node. The parent axis can only have one node for all other element nodes. So We need to traverse through the HTML tags down to desired target object. Next from a Parent Node starts with an element and down from that is child nodes then sub-nodes and lastly a child leaf node. When we consolidate all together, we would get XPath derived from which is shown below:
Let’s take input as
<Home>
<Flat id="11"/>
<Flat id="21">
<Flat id="12.1"/>
<Flat id="22.2"/>
<ground id="23.3"/>
</Flat >
<ground id="3"/>
</Home>
The XPath expression goes like this:
/Home/Flat[21]/A[21]/parent::Flat
A Parent of a context node is selected Flat element.
The result is
<Flat id="21">
<Flat id="12.1"/>
<Flat id="22.2"/>
<ground id="23.3"/>
</Flat>
To find a parent / getting nodes relative to the present node. Lets have a scenario like
<Author name="BenTracb" gender="male" country="India">
<book name="Python" cover="red" country="Japan">
<XX name="Tofen Ray" gender="male"/>
<BB name="Michael" gender="Female"/>
</book>
</Author>
The Xpath Expression goes like this
//XX/parent::node()
This gives the result as: <book name="Python" cover="red" country="Japan">
<XX name="Tofen Ray" gender="male"/>
<BB name="Michael" gender="Female"/>
</book>
A string of elements is normally separated by a slash in an XPath statement. You can pick the parent element by inserting two periods “..” where an element would typically be. The parent of the element to the left of the double period will be selected.
<Goods>
<cotton>
<dress supplier="wholesale" id="1">
<price>$5.50</price>
<amount>80</amount>
</cotton>
<buds supplier="weavers" id="2">
<price>$2.50</price>
<amount>100</amount>
</buds>
</cotton>
<Leather>
<bags supplier="weavers" id="3">
<price>$6.50</price>
<amount>90</amount>
<Kilograms>800</Kilograms>
</bags>
</Leather>
</Goods>
Selecting a parent with Xpath Expression: For example, if we need to select all the sale elements like leather, cotton normally we would give a few expressions like
Goods/Leather/bags or Goods/Leather/cotton.
This can be simplified by selecting the parent element of the amount to yield the same three sale elements. It is because all the products have the same element ‘amount’. Therefore, an expression goes like this:
Amount/…
This expression picks all of the needed elements in our XML document using a relative path location. It then selects the parent element of each amount element using the parent sequence “..”
Though XPath finds an element using different functions in many situations, few complex functions like ancestors, parent helps to retrieve an element simply.
Examples
Following examples can be considered to use the parent axes to traverse to the parent of an element. Let’s begin with the implementation of the parent Xpath axis along the path.
Example #1
As an example, consider the XML file below. A Tuition element is represented by a number of nodes in the File:
pp.xml
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<Tuition>
<!-- Comment: This is a list of student -->
<delegate idno = "190">
<firstname>Dinpam</firstname>
<lastname>Var</lastname>
<nickname>Nickil</nickname>
<Grade>81</Grade>
</delegate>
<delegate idno = "200">
<firstname>Edwin</firstname>
<lastname>Khoen</lastname>
<nickname>Vennice</nickname>
<Grade>97</Grade>
</delegate>
<delegate idno = "520">
<firstname>Jaysh</firstname>
<lastname>Singh</lastname>
<nickname>Donald</nickname>
<Grade>94</Grade>
</delegate>
</Tuition>
pp.xslt
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:template match = "/" >
<html>
<body>
<xsl:value-of select = "/Tuition/delegate/parent::comment()"/>
<br/>
<xsl:text>Initial Delegate: </xsl:text>
<xsl:value-of select = "/Tuition/delegate/parent::marks" />
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Explanation
Using XSLT the above parent axes is retrieved as shown below:
Output:
Example #2
<?xml version="1.0" encoding="utf-8"?>
<d:dval xmlns:d="defiant-namespace" d:mi="2">
<library d:mi="21">
<book price="13.99" d:price="Number" d:mi="40">
<btitle d:constr="String" d:mi="11">Harry Potter</btitle>
<sub-category d:constr="String" d:mi="21">fiction</sub-category>
<Writer d:constr="String" d:mi="31">Rose XXX</Writer>
</book>
<book price="18.99" d:price="Number" d:mi="50">
<btitle d:constr="String" d:mi="12">Comic battle</btitle>
<sub-category d:constr="String" d:mi="31">Adventerous</sub-category>
<Writer d:constr="String" d:mi="41">Mark XXX</Writer>
<isbn_no d:constr="String" d:mi="10">1-453-2251-3</isbn_no>
</book>
<book price="19.99" d:price="Number" d:mi="60">
<btitle d:constr="String" d:mi="11">Mummy returns</btitle>
<sub-category d:constr="String" d:mi="21">Action</sub-category>
<Writer d:constr="String" d:mi="31">Tom ZZZ</Writer>
</book>
<book price="18.99" d:price="Number" d:mi="58">
<btitle d:constr="String" d:mi="11">Family man</btitle>
<sub-category d:constr="String" d:mi="21">Family</sub-category>
<Writer d:constr="String" d:mi="31">Rajesh jay</Writer>
<isbn_no d:constr="String" d:mi="17">2-365-18465-8</isbn_no>
</book>
<car price="20.95" d:price="Number" d:mi="31">
<brand_name d:constr="String" d:mi="19">Hero</brand_name>
<color d:constr="String" d:mi="40">Pink</color>
</car>
</library>
</d:dval>
Explanation
Xpath parent is written as above using a specified Syntax format. Next, the Xpath expression retrieves the element as shown below:
Output:
Example #3
It displays the parent node. If it is single it takes up the parent element of the time hour which is clocks.
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Clocks timezone="GMT">
<timehour>10</timehour>
<timeminute>30</timeminute>
<timesecond>45</timesecond>
<timemeridian>a.m.</timemeridian>
</Clocks>
Explanation
The XML code above retrieves the Parent node in the tester by representing like parent: *and the result is given as a
Result:
Example #4
Parent.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.Node;
public class Parent
{
public static void main(String[] args) throws Exception
{
DocumentBuilderFactory docB = DocumentBuilderFactory.newInstance();
docB.setNamespaceAware(true);
DocumentBuilder db = docB.newDocumentBuilder();
Document dc = db.parse("D:/parser/shu.xml");
XPathFactory xpf = XPathFactory.newInstance();
XPath xpa = xpf.newXPath();
XPathExpression ex = xpa.compile("//Shuttler/parent::*");
Node parent = (Node) ex.evaluate(dc, XPathConstants.NODE);
System.out.println("The Shutters in the team are: ");
System.out.println("The Parent element is "+parent.getNodeName());
}
}
shu.xml
<?xml version="1.0" encoding="UTF-8"?>
<Shuttlers>
<Shuttler hand="righty">
<fname>Howard Shu</fname>
<role>Captain</role>
<country>USA</country>
</Shuttler>
<Shuttler hand="left">
<fname>Loh Kean Yew</fname>
<role>XXX</role>
<country>Singapore</country>
</Shuttler>
<Shuttler hand="righty">
<fname>Johanney</fname>
<role>Substitute</role>
<country>German</country>
</Shuttler>
<Shuttler hand="left">
<fname>Sindhu</fname>
<role>Captain</role>
<country>India</country>
</Shuttler>
</Shuttlers>
Explanation
The above java code accesses any tag of the parent using the parent axis. Here the path expression returns a list of nodes and the parent axis is represented as a parent::. The output displays as
Output:
Conclusion
Coming to an end, this article simply explains XPath parents. And we have also seen a few implementations of how to access a parent node effectively.
Recommended Articles
This is a guide to XPath parent. Here we discuss the Introduction, syntax, How does XPath parent works? examples with code implementation. You may also have a look at the following articles to learn more –