当前位置: 编程技术>.net/c#/asp.net
服务器端C#实现的CSS解析器
来源: 互联网 发布时间:2014-10-13
本文导语: 代码如下:using System; using System.Collections; using System.Text; using System.IO; using System.Collections.Specialized; using System.Text.RegularExpressions; using System.Diagnostics; namespace CSS { public class App { public static void Main(string[] args) { //初始化CSS解析器 CssDoc...
代码如下:
using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Diagnostics;
namespace CSS
{
public class App
{
public static void Main(string[] args)
{
//初始化CSS解析器
CssDocument doc = new CssDocument();
//加载现有CSS文件
doc.Load(Directory.GetCurrentDirectory() + "/test.css");
//修改CSS
doc["body"].Attributes["font-size"] = "12px";
//保存CSS文件
doc.Save(Directory.GetCurrentDirectory() + "/a.css");
Console.Read();
}
}
public class CssParse
{
private string m_source;
private int m_idx;
public static bool IsWhiteSpace(char ch)
{
return( "tnr ".IndexOf(ch) != -1 );
}
public void EatWhiteSpace()
{
while ( !Eof() )
{
if ( !IsWhiteSpace(GetCurrentChar()) )
return;
m_idx++;
}
}
public bool Eof()
{
return(m_idx>=m_source.Length );
}
public string ParseElementName()
{
StringBuilder element = new StringBuilder();
EatWhiteSpace();
while ( !Eof() )
{
if (GetCurrentChar()=='{')
{
m_idx++;
break;
}
element.Append(GetCurrentChar());
m_idx++;
}
EatWhiteSpace();
return element.ToString().Trim();
}
public string ParseAttributeName()
{
StringBuilder attribute = new StringBuilder();
EatWhiteSpace();
while ( !Eof() )
{
if (GetCurrentChar()==':')
{
m_idx++;
break;
}
attribute.Append(GetCurrentChar());
m_idx++;
}
EatWhiteSpace();
return attribute.ToString().Trim();
}
public string ParseAttributeValue()
{
StringBuilder attribute = new StringBuilder();
EatWhiteSpace();
while ( !Eof() )
{
if (GetCurrentChar()==';')
{
m_idx++;
break;
}
attribute.Append(GetCurrentChar());
m_idx++;
}
EatWhiteSpace();
return attribute.ToString().Trim();
}
public char GetCurrentChar()
{
return GetCurrentChar(0);
}
public char GetCurrentChar(int peek)
{
if( (m_idx+peek)