tags:

views:

149

answers:

1

Hi everyone,

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.

A: 

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

  • all ROLEs that are descendant of /ROLES ("/ROLES//ROLE")…
  • …that have @type='C' ("/ROLES//ROLE[@type='C']")…
  • …of their USER children those that have @name='x' (/USER[@name='x'])
  • …and going from there all ancestor-or-self::USERs having @name='x'

the last location step breaks it. There are no USER ancestors, only ROLE ancestors.

Tomalak
Indeed, none of the USER nodes actually has children.
0xA3
Thanks a lot divo. You got it right before my clarification. (Sorry for somewhat ambiguous description)