I am self-studying XPath from Pro XML Development with Java. Just for practice I have constructed a sample XML document and some XPath expressions.
Below are a few XPath expressions along with their explanations and a few related questions. Please correct me if my explanations are wrong and answer the questions wherever applicable.
XML
<?xml version="1.0" encoding="UTF-8" ?>
<people>
<student scholarship="Yes">
<name>John</name>
<course>Computer Technology</course>
<semester>6</semester>
<scheme>E</scheme>
</student>
<student>
<name>Foo</name>
<course>Industrial Electronics</course>
<semester>6</semester>
<scheme>E</scheme>
</student>
<grumpy-cat>
<soup-noodle>
<student>
<name>Dingle</name>
<course>Grumpiness</course>
<semester>3</semester>
<scheme>E</scheme>
</student>
</soup-noodle>
</grumpy-cat>
</people>
Expression 1: /people/student[@scholarship='Yes']/name
Explanation: Will select the elements <name>..</name>
which are contained in <people>
such that <student>
has an attribute named scholarship
with a value of Yes
Question: Will this also select the value John in it ????
Expression 2: /people/student[2]
Explanation: Will select the element <student>..</student>
which is at the 2nd position in the element <people>
Question: Will it also select the child nodes within ?
Expression 3: /people/student/@scholarship
Explanation: Will select the attribute scholarship in the element student. If there were multiple <student scholarship="">
then it would select multiple attributes
Expression 4: //name[ancestor::student]
Explanation: Will select all the <name>..</name>
elements//
means 'all-the-descendants'. In my context it means 'I don't care who the descendants are
as long as my immediate ancestor is student'