How to select sibling elements in XPath?

To select sibling elements in XPath the preceding-sibling and following-sibling axes can be used - see these interactive examples:

  1. preceding-sibling::span will select any siblings that precede (i.e. are above) the current element:
<!-- we can find tax rate by navigating from price--> <div> <article> <h1>title</h1> <p>paragraph</p> <span>(no tax)</span> <h3>2.99</h3> </article> </div>
  1. following-sibling::span will select siblings that follow (i.e. are below) the current element:
<!-- we can find currency by navigating from price--> <div> <article> <h1>title</h1> <p>paragraph</p> <p>paragraph with <a href="/foo.html">link</a></p> <span>(no tax)</span> <h3>2.99</h3> <span>USD</span> </article> </div>

Note that the wildcard character can be used instead of explicit element names (e.g. following-sibling::*) to select siblings of any element name.

For more on XPath, see our full introduction article

Question tagged: XPath

Related Posts

How to Parse XML

In this article, we'll explain about XML parsing. We'll start by defining XML files, their format and how to navigate them for data extraction.

Ultimate XPath Cheatsheet for HTML Parsing in Web Scraping

Ultimate companion for HTML parsing using XPath selectors. This cheatsheet contains all syntax explanations with interactive examples.

Web Scraping With Ruby

Introduction to web scraping with Ruby. How to handle http connections, parse html files for data, best practices, tips and an example project.