using System.Collections.Generic;
namespace CSS
{
public class Item
{
public string Class { get; set; }
public int Left { get; set; }
public int Top { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string Image { get; set; }
}
public class Parser
{
string m_cssString;
List- m_items;
public Parser()
{
m_items = new List
- ();
}
public void parseCss(string css)
{
// remove all useless stuff and get the relevant tokens
string[] tokens = css.Replace("\n", "").Replace("\t", "").Replace("\r", "").Replace(" ", "").Replace("px", "").Split('{', '}', ';');
m_cssString = css;
foreach (string token in tokens)
{
Item last = null;
if (m_items.Count > 0)
{
last = m_items[m_items.Count - 1];
}
if (token != string.Empty)
{
if (token.StartsWith("."))
{
// class found
m_items.Add(new Item() { Class = token.Substring(1) });
}
else if (token.StartsWith("left") && last != null)
{
last.Left = int.Parse(token.Split(':')[1]);
}
else if (token.StartsWith("top") && last != null)
{
last.Top = int.Parse(token.Split(':')[1]);
}
else if (token.StartsWith("width") && last != null)
{
last.Width = int.Parse(token.Split(':')[1]);
}
else if (token.StartsWith("height") && last != null)
{
last.Height = int.Parse(token.Split(':')[1]);
}
else if (token.StartsWith("background-image") && last != null)
{
last.Image = token.Split('"')[1];
}
}
}
}
public List
- getItems()
{
return m_items;
}
}
}
Montag, 2. Februar 2015
Simple CSS Parser in C#
The example below describes a simple CSS text parser to get certain values from CSS-class definitions:
Abonnieren
Kommentare (Atom)