使用SAC&CSSParser解析css文件简单示例

SAC:

http://www.w3.org/Style/CSS/SAC/

 

CSSParser下载地址

http://sourceforge.net/projects/cssparser/files/

 

Sample Code:

import java.io.IOException;

import org.w3c.css.sac.InputSource;
import org.w3c.dom.css.CSSImportRule;
import org.w3c.dom.css.CSSRule;
import org.w3c.dom.css.CSSRuleList;
import org.w3c.dom.css.CSSStyleDeclaration;
import org.w3c.dom.css.CSSStyleRule;
import org.w3c.dom.css.CSSStyleSheet;

import com.steadystate.css.parser.CSSOMParser;

public class CSSParserTest {
	public static void main(String[] args)   
    {   String URIPath = "file:///" + "d:/common.css";  
		CSSOMParser cssparser = new CSSOMParser();   
        CSSStyleSheet css = null;   
        try {
			css = cssparser.parseStyleSheet(new InputSource(URIPath), null,
					null);
		} catch (IOException e) {
			System.out.println("解析css文件异常:" + e);
		}
		if(css!=null){
			CSSRuleList cssrules = css.getCssRules(); 
	        for (int i = 0; i < cssrules.getLength(); i++){ 
	        	CSSRule rule = cssrules.item(i);   
	            if (rule instanceof CSSStyleRule){
	            	CSSStyleRule cssrule = (CSSStyleRule) rule;
	            	System.out.println("cssrule.getCssText:"+cssrule.getCssText());
	            	System.out.println("cssrule.getSelectorText:"+cssrule.getSelectorText());
	            	CSSStyleDeclaration styles=cssrule.getStyle();
	            	for(int j=0,n=styles.getLength();j<n;j++){
	            		System.out.println(styles.item(j)+":"+styles.getPropertyValue(styles.item(j)));
	            	}
	            	
	            }else if (rule instanceof CSSImportRule){
	            	 CSSImportRule cssrule = (CSSImportRule) rule;  
	            	 System.out.println(cssrule.getHref());
	    		}
	        }
		}
  
    }
}

  

发现存在的问题:

对于非css2标准样式不能识别,如:

-moz-opacity:100;

filter:alpha(opacity=100);

你可能感兴趣的:(.net,css,J#)