As you learned about descendant axis in XPath expression in the previous example, this section will illustrate the use of ancestor in XPath expression. "ancestor" selects parent element or ancestor of the context node and super-parent of that parent.
In this example we have created an XML file "persons.xml" as in our previous section, which is necessary to execute XPath query on to it. This "persons.xml" contains information related to name, age, gender of different persons.
Here is the full source code for persons.xml file as follows :
persons.xml
<?xml version="1.0" ?> |
Now we have declared a class XPathAncestor class and in this class we are parsing the XML file with JAXP. First of all we need to load the document into DOM Document object. We have put that persons.xml file in that current working directory.
DocumentBuilderFactory domFactory = |
Above lines of code parses "persons.xml" file and creates a Document object. Next we have created XPath object with the use of XPathFactory.
XPath xpath = XPathFactory.newInstance().newXPath(); |
XPath expression "//person/ancestor::*" will select parent or ancestor of person as well as ancestor of person.
Here is full example code for XPathAncestor.java as follows:
XPathAncestor.java
import org.w3c.dom.*;
|

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Use of "ancestor" in XPath expression
Post your Comment