Dipak
Dipak

Reputation: 443

XPath select specific child elements

If I have XML tree like this-

<Parent>
 <Image Name="a"/>
 <Image Name="b"/>
 <Child>
  <Image Name="c"/>
  <Image Name="d"/>
 </Child>
 <SomeElem>
  <Image Name="h"/>
  <Image Name="g"/>
 </SomeElem>
 <Image Name="e"/>
</Parent>

I want to select all <Image\> nodes except those listed inside <Child\> node. Currently I am using query to select all Image nodes, -

xElement.XPathSelectElements("//ns:Image", namespace);

Thanks in advance.

Upvotes: 2

Views: 2678

Answers (3)

Anurag
Anurag

Reputation: 141899

get all Image elements, whose parent is not a Child.

//*[not(self::Child)]/Image

Edit 1: This one below won't work as Parent is also selected in the process, which is not a Child, and Image is one of the descendants (through Child).

you could also get all Image elements, whose ancestor is not a Child

//*[not(self::Child)]//Image

Edit 2: This probably works best for all cases. It gets all Image nodes who are not descendants of Child.

//Image[not(ancestor::Child)]

Upvotes: 3

Matti Virkkunen
Matti Virkkunen

Reputation: 65166

/ns:Parent/ns:Image should do the trick

Upvotes: 0

Kaleb Pederson
Kaleb Pederson

Reputation: 46499

If you only want to select those at the root level, then you can just do:

xElement.XPathSelectElements("/ns:Image", namespace);

The // tells the xpath engine to look at all Image nodes, no matter their depth.

Upvotes: 0

Related Questions