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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)