Supported XPath Expressions

cagdasgerede edited this page Apr 7, 2011 · 7 revisions

Here are some samples of XPath use in Hpricot:

 require 'hpricot'
 require 'open-uri'
 doc = Hpricot(URI.parse("").read)"/html/body//p")"//p")"//p/a")"//a[@src]")"//a[@src='']")

Location Paths

Absolute Paths"/html/body//p")"/*/body//p")"//p/../div")

Relative Paths"a",this)"p/a",this)

Supported Axes


Element has a descendant element."//div/descendant::p")

Identical to"//div//p") .


Element has a child element."//div/child::p")

Which is identical to:"//div/p") .


Element has an element before it, on the same axes."//div/preceding-sibling::form")


Selects the parent element of the element"//div/parent::div")

Which is identical to"//div/../div") .


Selects the element itself.

Supported Predicates

  • [@*] Has an attribute"//div[@*]"))
  • [@foo] Has an attribute of foo"//input[@checked]"))
  • [@foo='test'] Attribute foo is equal to test"//a[@ref='nofollow']")@)
  • [Nodelist] Element contains a node list, for example:"//div[p]")"//div[p/a]")

Supported Predicates, but differently

  • [last()] or [position()=last()] becomes :last"p:last")
  • [0] or [position()=0] becomes :eq(0) or :first"p:first")"p:eq(0)")
  • [position() < 5] becomes :lt(5)"p:lt(5)")
  • [position() > 2] becomes :gt(2)"p:gt(2)")