12

Say I have the following UL:

<ul>
  <li>barry</li>
  <li>bob</li>
  <li>carl</li>
  <li>dave</li>
  <li>roger</li>
  <li>steve</li>
</ul>

I need to grab all the LIs between bob & roger. I can grab everything after bob with //ul/li[contains(.,"bob")]/following-sibling::li, and I can grab everything before roger with //ul/li[contains(.,"roger")]/preceding-sibling::li. The problem is when I try to combine the two, I end up getting extra results.

For example, //ul/li[contains(.,"bob")]/following-sibling::li[contains(.,"roger")]/preceding-sibling::li will of course get everything before roger, instead of ignoring the items before bob.

Is there a way to chain these two xpaths together?

MrGlass
  • 9,094
  • 17
  • 64
  • 89

1 Answers1

21

Try:

/ul/li[preceding-sibling::li='bob' and following-sibling::li='roger']
Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
  • Dastardly exploitation of the conversion rules. :) – biziclop Mar 26 '12 at 21:01
  • 1
    @biziclop - Not sure what you mean. Do you mean the part where I do `li='bob'` or `li='roger'`? It could also be done like this: `/ul/li[preceding-sibling::li[.='bob'] and following-sibling::li[.='roger']]`. (`contains()` could also be used in those li predicates) – Daniel Haley Mar 26 '12 at 21:04
  • 3
    Yes, that's what I meant, but I wasn't complaining, I was applauding. – biziclop Mar 26 '12 at 21:05
  • @DanielHaley Hi, im using a file where the order of the siblings is not guranteed (they can be in any order). I see there is syntax for `preceeding-sibling` and `following-sibling` but is there syntax for `in-the-same-node-as-sibling-with-text` ? – Just a coder Oct 11 '15 at 19:13
  • @Jai - I'm not sure what you mean. I recommend creating a new question with a clear example. – Daniel Haley Oct 11 '15 at 19:15