Renjith
Renjith

Reputation: 1154

Read attribute of a parent/ancestor node using xpath axes

I am trying to read the 'division' attribute of 'class' node from 'student' node using XPath & XSLT.

<class division="myDiv">
    <student rollno="700">
        <firstname>Renjith</firstname>
        <lastname>R</lastname>
        <nickname>Renju</nickname>
        <marks>70</marks>
    </student>
    <student rollno="493">
        <firstname>fname1</firstname>
        <lastname>lname1</lastname>
        <nickname>nick1</nickname>
        <marks>95</marks>
    </student>
</class>

my condition is, if the firstname is 'Renjith', read the 'division' attribute of 'class' node, which i believe is a parent node of student node.

i used the following xpath to check if the first name is 'Renjith'

//student[firstname/text() = 'Renjith']

I am at student node whose first name is 'Renjith'.Now i need to get the value of division attribute from 'class' node, who is the parent of student node. i could achieve the result using the following xpath expressions.

1)parent::class/@division
or
2)ancestor::class/@division

I got two questions here.
1. what is the difference b/w expressions 1 & 2?
2. is there any way i could get the 'division' attribute with out specifying the parent node name 'class'? I know '../@division' can do the trick. but my intention is to study the xpath axes.

Upvotes: 0

Views: 294

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

.. is a shortcut for parent::node() so parent::node()/@division is the verbose way of using the parent axis, if you insist on doing it that way. As for ancestor::class, if you had nested <class><class><student>..</student></class></class> elements (which semantically probably does not make sense for your data but is possible in general in XML) then ancestor::class selects both ancestorclasselements whileparent::classselects only the parentclass`.

Upvotes: 1

Related Questions