Use Nokogiri to convert CSS to XPath

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.

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.

Arne Hartherz Almost 12 years ago