awj
awj

Reputation: 7949

Parse CSS out from <style> elements

Can someone tell me an efficient method of retrieving the CSS between tags on a page of markup in .NET?

I've come up with a method which uses recursion, Split() and CompareTo() but is really long-winded, and I feel sure that there must be a far shorter (and more clever) method of doing the same.

Please keep in mind that it is possible to have more than one element on a page, and that the element can be either or .

Upvotes: 1

Views: 5841

Answers (3)

tcables
tcables

Reputation: 1307

Try Regex.

goto:http://gskinner.com/RegExr/ paste html with css, and use this expression at the top:

<style type=\"text/css\">(.*?)</style>

here is the c# version:

using System.Text.RegularExpressions;

Match m = Regex.Match(this.textBox1.Text, "<style type=\"text/css\">(.*?)</style>", RegexOptions.Singleline);

if (m.Success)
{
    string css = m.Groups[1].Value;
    //do stuff
}

Upvotes: 0

Matthew Dresser
Matthew Dresser

Reputation: 11442

I'd probably go for HTML Agility Pack which gives you DOM style access to pages. It would be able to pick out your chunks of CSS data, but not actually parse this data into key/value pairs. You can get the relevant pieces of HTML using X-Path style expressions.

Edit: An example of typical usage of Html Agility Pack is shown below.

HtmlDocument doc = new HtmlDocument();
doc.Load("file.htm");
var nodes = doc.DocumentElement.SelectNodes("//a[@style"]);
//now you can iterate over the selected nodes etc

Upvotes: 3

Samuel Neff
Samuel Neff

Reputation: 74909

Here's a C# CSS parser. Should do what you need.

http://www.codeproject.com/KB/recipes/CSSParser.aspx

Upvotes: 1

Related Questions