Home > front end >  Xpath to find element with child X with no intervening text, and no child Y
Xpath to find element with child X with no intervening text, and no child Y

Time:02-07

With this:

<p>Some variable length text <abbr>abc</abbr> and more text.</p>
<p><abbr>abc</abbr>Some variable length text.</p>
<p><abbr>abc</abbr>Some variable length text. <a href="somelink">blah</a></p>

I'm trying to build an Xpath that will find p elements that:

  1. Have a child <abbr> with value of "abc", but that child has no intervening text between the parent and the child.
  2. Does not have a child <a>.

#1 means the first line should not match, because it has text between the parent <p> and the child <abbr>. #2 means the third line should not match, because although there is a child <abbr> and no intervening text, it also has a child <a>.

Thus, only line #2 should match: no intervening text, and no child <a>.

I've played with an XPath testbed for an hour, and done quite a bit of searching, but haven't figured out how to handle both of those requirements, but especially #1.

CodePudding user response:

This XPath,

//p[node()[1][self::abbr]='abc'][not(a)]

selects all p elements

  1. with a first sibling abbr element that has a string value of "abc"1, and
  2. without an a child,

as requested.


1 Note that #1 implies that abbr must be the first node, which prevents any node (text, another element, etc) from be a previous sibling to abbr.

CodePudding user response:

Try this XPath-1.0 expression:

//p[node()[1]!=text()[1] and abbr='abc' and not(a)]

It checks if the first child node is a text() node. Further checks are that it has a child "abbr" with the content 'abc' and no children named "a".

  •  Tags:  
  • Related