9

Is there a library out there that will allow me to write the following kind of code, which parses CSS and returns a queryable object model

string input = "p, span { font-family: arial; }";
var cssRules = new Parser().Parse(input);
var rule = cssRules.Find(new Selector("p")).First();

Assert.That(rule.Attribute("font-family").Value, Is.Equal.To("arial"));

I've taken a look at dotless, downloaded their code and examined some of the relevant unit tests and fixtures. It looks promising but I can't quite work out how to use it to parse and query plain CSS.

madth3
  • 7,275
  • 12
  • 50
  • 74
Edward Wilde
  • 25,967
  • 8
  • 55
  • 64
  • 1
    `Assert.That(rule.Attribute("font-family").Value, Is.Equal.To("arial"));` is awfully neat. What library does that come from? – Eric Jul 25 '11 at 13:13
  • @Eric [NUnit](http://en.wikipedia.org/wiki/Nunit) (the ['constraint' model](http://www.nunit.org/index.php?p=constraintModel&r=2.5.10) ) – AakashM Jul 25 '11 at 14:17
  • You could also take a look at the Microsoft AJAX Minifier (http://ajaxmin.codeplex.com/). It includes source code for building a complete, in-memory representation of a CSS file. No support for querying, but it could be an option for the parsing part of the problem. Another bonus is that if you hook it up to your builds, it will validate the syntax of the CSS file and emit errors and warnings just like any other compiler. – ShadowChaser Jul 25 '11 at 18:05

1 Answers1

1

The closest I know is CssParser from jsonfx.net:

http://css-parser.googlecode.com/svn/trunk/CssParser/

You can parse any css and browse through selectors afterwards using StyleSheet property of CssParser

michalczerwinski
  • 1,069
  • 9
  • 6
  • Yep, this works. Syntax is a bit awkward for what I'm trying to do, but butter than writing my own code :) Thanks for the link. – Edward Wilde Jul 26 '11 at 14:40