Tuesday 23 September 2008

CSS Parser



Presenting to you a simple piece of code that parses CSS. It uses Regular Expressions to achieve the functionality.



The sample code below gives you an idea how to use it.



/*
*
* Date Created: 02-Sep-2008
* Author: SAHAY, Sanjeet, IDC
* Filename: CssParserFixture.cs
* Assembly: Sanjeet.Demos
* Project: Demos



* Purpose: Add purpose
*
*/
using System.Collections.Generic;
using NUnit.Framework;
using Sanjeet.Demos.CSSParser;

namespace Sanjeet.Demos
{
[TestFixture]
public class CssParserFixture
{
private IDictionary<string, string> properties;

private IContainer GetContainer()
{
const string cssFilepath = @"..\..\..\CssParser\StyleSheet.css";
return new DefaultContainer(cssFilepath);
}

[Test]
public void GetButtonsClip()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("Buttons");
Assert.IsTrue(this.properties["clip"].Equals("rect(auto auto auto auto)"));
}

[Test]
public void GetButtonsPropertiesCount()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("Buttons");
Assert.IsTrue(this.properties.Count == 16);
}

[Test]
public void GetH1Color()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("H1");
Assert.IsTrue(this.properties["color"].Equals("blue"));
}

[Test]
public void GetH1FontStyle()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("H1");
Assert.IsTrue(this.properties["font-style"].Equals("italic"));
}

[Test]
public void GetH1PropertiesCount()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("H1");
Assert.IsTrue(this.properties.Count == 2);
}

[Test]
public void GetMasterTablePropertiesCount()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("MasterTable");
Assert.IsTrue(this.properties.Count == 8);
}

[Test]
public void GetNameLabelPropertiesCount()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("NameLabel");
Assert.IsTrue(this.properties.Count == 4);
}

[Test]
public void GetUL()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("UL");
Assert.IsTrue(this.properties.Count == 4);
}

[Test]
public void GetULFontWeight()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("UL");
Assert.IsTrue(this.properties["font-weight"].Equals("bold"));
}
}
}

1 comment:

Anonymous said...

It seems RegEx is wrong and fails to identify element properly.

Example:
CSS file has next:
.content .summaryTable td { text-align: left; width: 170px; }
.content .summaryTable td.col3 { width: 470px; }

Code:
this.properties = container.GetProperties(".content .summaryTable td");

fails because regex matches both styles above and tried to add width attribute twice.