Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.81 KB | None | 0 0
  1. public class CSSParser
  2. {
  3.     const string CSSComments = @"(?<!"")\/\*.+?\*\/(?!"")";
  4.     const string CSSGroups = @"(?<selector>(?:(?:[^,{]+),?)*?)\{(?:(?<name>[^}:]+):?(?<value>[^};]+);?)*?\}";
  5.  
  6.     //return the contents of a single css file, broken up into classes
  7.     public static CSSData ReadCSS(string cssPath)
  8.     {
  9.         string cssString = File.ReadAllText("Assets/Resources/OEBPS/"+cssPath);    
  10.         cssString = Regex.Replace(cssString, CSSComments, "");
  11.        
  12.         Regex rStyles = new Regex(CSSGroups, RegexOptions.IgnoreCase);
  13.         char[] whiteSpace = {'\r','\n','\f','\t','\v'};
  14.        
  15.         MatchCollection MatchList = rStyles.Matches(cssString);
  16.         CSSData CSS = new CSSData();
  17.         CSS.Path = cssPath;
  18.        
  19.         foreach(Match item in MatchList)
  20.         {
  21.             if (item != null && item.Groups != null && item.Groups["selector"] != null && item.Groups["selector"].Captures != null &&
  22.                 item.Groups["selector"].Captures[0] != null && !string.IsNullOrEmpty(item.Groups["selector"].Value))
  23.             {
  24.                 string Selector = item.Groups["selector"].Captures[0].Value.Trim();
  25.                 List<KeyValuePair<string, string>> Style = new List<KeyValuePair<string, string>>();
  26.                
  27.                 for(int i = 0; i < item.Groups["name"].Captures.Count; i++)
  28.                 {
  29.                     string Class = item.Groups["name"].Captures[i].Value;
  30.                     string Value = item.Groups["value"].Captures[i].Value;
  31.                    
  32.                     if (!string.IsNullOrEmpty(Class) && !string.IsNullOrEmpty(Value))
  33.                     {
  34.                         Class = Class.Trim(whiteSpace).Trim();      //trim regular spaces plus \n etc.
  35.                         Value = Value.Trim(whiteSpace).Trim();
  36.                        
  37.                         if (!string.IsNullOrEmpty(Class) && !string.IsNullOrEmpty(Value))
  38.                             Style.Add(new KeyValuePair<string, string>(Class, Value));
  39.                     }
  40.                 }
  41.                
  42.                 CSS.CSS.Add(new KeyValuePair<string, List<KeyValuePair<string, string>>>(Selector,Style));
  43.             }
  44.         }
  45.        
  46.         return CSS;
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement