KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I need to inline css from a stylesheet in c#. Like how this works. http://www.mailchimp.com/labs/inlinecss.php The css is simple, just classes, no fancy selectors. I was contemplating using a regex (?<rule>(?<selector>[^{}]+){(?<style>[^{}]+)})+ to strip the rules from the css, and then attempting to do simple string replaces where the classes are called, but some of the html elements already have a style tag, so I'd have to account for that as well. Is there a simpler approach? Or something already written in c#? UPDATE - Sep 16, 2010 I've been able to come up with a simple CSS inliner provided your html is also valid xml. It uses a regex to get all the styles in your <style /> element. Then converts the css selectors to xpath expressions, and adds the style inline to the matching elements, before any pre-existing inline style. Note, that the CssToXpath is not fully implemented, there are some things it just can't do... yet. CssInliner.cs using System.Collections.Generic; using System.Text.RegularExpressions; using System.Xml.Linq; using System.Xml.XPath; namespace CssInliner { public class CssInliner { private static Regex _matchStyles = new Regex("\\s*(?<rule>(?<selector>[^{}]+){(?<style>[^{}]+)})", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled ); public List<Match> Styles { get; private set; } public string InlinedXhtml { get; private set; } private XElement XhtmlDocument {
Tags (comma-separated)
Save Edits
Cancel