stefkey stefkey - 1 year ago 224
HTML Question

XPath to select tags near (before and after) another element?

It is possible to select all

tags before and after an
element with XPath?

This selects only the first

Here is a code snippet, I would like to select the 2
tags before and the 2
tags after the

<br />22111 Hamburg<br />(U- und Busbahnhof Billstedt)<br /><br /><h3>Wir treffen uns</h3><br /><br />um Erfahrungen auszutauschen...

Answer Source


  1. You probably don't mean all h3 elements but rather one particular h3 element.
  2. [1] is causing only the next following sibling to be selected.
  3. Rather than *[name()='br'], use br.
  4. Be sure you mean following-sibling, not following.

Then this XPath,


will select all br elements are siblings to the h3 element whose string value is Heading.


For this HTML,

   <br/>22111 Hamburg<br/>
   (U- und Busbahnhof Billstedt)
   <h3>Wir treffen uns</h3>
   um Erfahrungen auszutauschen...

this XPath will select the two br sibling elements immediately before the targeted h3,

//h3[.='Wir treffen uns']/preceding-sibling::br[position() < 3]

this XPath will select the two br sibling elements immediately after the targeted h3,

//h3[.='Wir treffen uns']/following-sibling::br[position() < 3]

If you want to grab all 4 at the same time, you can combine the before and after XPath expressions above via |:

//h3[.='Wir treffen uns']/preceding-sibling::br[position() < 3]
//h3[.='Wir treffen uns']/following-sibling::br[position() < 3]

Update 2

If you want the number range to include all nodes, not just br elements, when counting, then use this XPath:

//h3[.='Wir treffen uns']/preceding-sibling::node()[position() < 3][self::br]
//h3[.='Wir treffen uns']/following-sibling::node()[position() < 3][self::br]

This works by testing node() position first, then making sure that those nodes within range are br elements via [self::br]. Be aware that all text nodes will count, even ones containing only whitespace.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download