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 u开发者_如何学编程p 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 .
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
Here's a C# CSS parser. Should do what you need.
http://www.codeproject.com/KB/recipes/CSSParser.aspx
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
}
精彩评论