I have the following xml:
<?xml version="1.0" encoding="utf-8" ?>
<ROLES>
<ROLE type="A">
<USER name="w" />
<USER name="x" />
<ROLE type="B">
<USER name="x" />
<USER name="y" />
</ROLE>
<ROLE type="C">
<USER name="x" />
<USER name="y" />
<USER name="z" />
</ROLE>
</ROLE>
<ROLE type ="D">
<USER name="w" />
</ROLE>
</ROLES>
and I want to find all USER nodes with name="x" and which are immediate children of ROLE nodes with attribute "type" equals "C" and their ancestors with name="x" (probably by using ancestor-or-self axis). In this case, the nodeset should
contain two nodes (not three, since the occurrence of x under B should
not count).
What is the correct XPath expression that would do it? Why doesn't the following expression work?
/ROLES//ROLE[@type='C']/USER[@name='x']/ancestor-or-self::USER[@name='x']
(this returns only one node, probably the self axis, and not the ancestors)
Any help will be most appreciated.
I want to find all USER nodes with name="x"…
//USER[@name = 'x']
…which are immediate children of ROLE nodes with attribute "type" equals "C"…
//USER[@name = 'x' and parent::ROLE[@type = 'C']]
…and their ancestors with name="x".
?
I don't see any ancestors that could possibly have the name="x". What do you mean?
EDIT: Ah, I think I understand. What you mean is:
…and their ancestor's children that are USERs with the name="x"
//USER[@name = 'x' and parent::ROLE[@type = 'C']]/ancestor::ROLE/USER[@name = 'x']
And now for the question why your XPath doesn't work:
/ROLES//ROLE[@type='C']/USER[@name='x']/ancestor-or-self::USER[@name='x']
selects
ROLEs that are descendant of /ROLES ("/ROLES//ROLE")…@type='C' ("/ROLES//ROLE[@type='C']")…@name='x' (/USER[@name='x'])ancestor-or-self::USERs having @name='x'the last location step breaks it. There are no USER ancestors, only ROLE ancestors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With