开发者

XPath select specific child elements

开发者 https://www.devze.com 2022-12-25 21:00 出处:网络
If I have XML tree like this- <Parent> <Image Name=\"a\"/> <Image Name=\"b\"/> <Child>

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"/>
</P开发者_运维知识库arent>

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.


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)]


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号