Use Nokogiri to convert CSS to XPath

Updated . Posted . Visible to the public.

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
Last edit
Michael Leimstädtner
Keywords
generate
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2012-06-26 19:00)