Read more

Use Nokogiri to convert CSS to XPath

Arne Hartherz
June 26, 2012Software engineer at makandra GmbH

CSS is a lot easier to write and read than clumsy XPath expressions. So when you need to use XPath, you can have Nokogiri help you out on creating it.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Simply use Nokogiri's xpath_for:

>> Nokogiri::CSS.xpath_for('#foo')
=> ["//*[@id = 'foo']"]
>> Nokogiri::CSS.xpath_for('#foo .bar:nth-of-type(2)')
=> ["//*[@id = 'foo']//*[contains(concat(' ', @class, ' '), ' bar ') and position() = 2]"]

Since XPath is more powerful you may still need to do some hardcore XPath hacking eventually. But at least you don't need to for simple cases.

Posted by Arne Hartherz to makandra dev (2012-06-26 21:00)