Here I am going to explain how to parse CSS file in c# and class name and attributes used in the css file
Step 1.
Get list of classes used in style sheet
string data= System.IO.File.ReadAllText(Server.MapPath("styles/StyleSheet1.css"));
MatchCollection mt = Regex.Matches(data, @"[^}]?([^{]*{[^}]*})", RegexOptions.Multiline);
List<string> className = new List<string>();
foreach (Match m in mt)
{
string mts = m.Captures[0].ToString();
string[] words = mt.Split('{');
string name = words[0];
className .Add(name);
}
Step 2.
Get list of attributes used in class
internal static IEnumerable<CssDeclaration> Parsedata(string data)
{
const string dataPattern = @"\s*(?<Property>.+?):\s*(?<Value>.+?);";
var dataMatches = Regex.Matches(data, dataPattern , RegexOptions.ExplicitCapture);
var result = dataMatches.Cast<Match>()
.Select(m => new CssDeclaration
{
Property = m.Groups["Property"].Value,
Value = m.Groups["Value"].Value
});
return result;
}
Step 3.
public class CssDeclaration
{
public string Property { get; set; }
public string Value { get; set; }
public override string ToString()
{
return $"{Property}: {Value};";
}
}
No comments:
Post a Comment