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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)