Ancestor

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 child ROLE nodes with the type attribute equal to "C" and their ancestors with name="x"(possibly using the axis of the ancestor or own), In this case, the set of nodes should contain two nodes (not three , since the appearance of x under B should not count).

What is the correct XPath expression to do this? Why does the following expression not work?

/ROLES//ROLE[@type='C']/USER[@name='x']/ancestor-or-self::USER[@name='x']

(this returns only one node, possibly the axis itself, not the ancestors)

Any help would be greatly appreciated.

+3
source share
1 answer

I want to find all USER nodes with name = "x" ...

// USER [@name = 'x']

... ROLE "", "C"...

//USER[@name = 'x' and parent::ROLE[@type = 'C']]

... name= "x".

?

, name= "x". ?


EDIT: , , . :

... , USER name= "x"

//USER[@name = 'x' and parent::ROLE[@type = 'C']]/ancestor::ROLE/USER[@name = 'x']

, XPath :

/ROLES//ROLE[@type='C']/USER[@name='x']/ancestor-or-self::USER[@name='x']

  • all ROLE, /ROLES ("/ROLES//ROLE")...
  • ... @type='C' ( "/ROLES//ROLE [@type = 'C']" )...
  • ... USER , @name='x' (/USER[@name='x'])
  • ... ancestor-or-self::USER @name='x'

. USER, ROLE.

+5

Source: https://habr.com/ru/post/1708164/


All Articles