While working with HtmlAgilityPack to build a web scrapper/crawler, I noticed something: I hate XPath. It’s big, clunky, and verbose. After a bit of searching, I found a neat online app: http://css2xpath.appspot.com/. As the name suggests, it converts CSS selectors to XPath selectors. The only problem is that I wanted a client-side solution.
A little more searching, and I find css2xpath. It accomplishes the same thing as the web service, but does it client side, in JavaScript. So, I ported it to C#. And here we are.
The original css2xpath, written by Andrea Giammarchi, is a single JavaScript function that uses a series of Regexes to transform a CSS selector, step-by-step, into an XPath selector. My version does the same thing, and uses the same Regexes and transformation functions, but is written in C#.
Housed in a single static class, the handful of functions contained within are easy to use. For example:
css2xpath.Transform('#id');
Is all that it takes. That expression will yield: //*[@id='anID']
.
Other features include the ability for you to define your own transformation rules. See the link below for more information and how to download. Enjoy!
Download/read about it at BitBucket: https://bitbucket.org/MostThingsWeb/css2xpath
Leave a comment