我正在寻找 java 中的 CSS 解析器。特别是,我的要求是,对于 HTML 文档中的给定节点/元素,能够从解析器询问/获取该元素的 css 样式。
我知道有 W3C SAC 接口和基于此的一两个实现 - 但图解/示例似乎不存在。
非常感谢任何帮助/指出正确方向。
Thanks
我用过CSS解析器我喜欢它——它也对错误提供了很好的反馈。
这是我找到并修改的一些示例代码:
package com.dlogic;
import com.steadystate.css.parser.CSSOMParser;
import org.w3c.css.sac.InputSource;
import org.w3c.dom.css.CSSStyleSheet;
import org.w3c.dom.css.CSSRuleList;
import org.w3c.dom.css.CSSRule;
import org.w3c.dom.css.CSSStyleRule;
import org.w3c.dom.css.CSSStyleDeclaration;
import java.io.*;
public class CSSParserTest
{
protected static CSSParserTest oParser;
public static void main(String[] args) {
oParser = new CSSParserTest();
if (oParser.Parse("design.css")) {
System.out.println("Parsing completed OK");
} else {
System.out.println("Unable to parse CSS");
}
}
public boolean Parse(String cssfile)
{
FileOutputStream out = null;
PrintStream ps = null;
boolean rtn = false;
try
{
// cssfile accessed as a resource, so must be in the pkg (in src dir).
InputStream stream = oParser.getClass().getResourceAsStream(cssfile);
// overwrites and existing file contents
out = new FileOutputStream("log.txt");
if (out != null)
{
//log file
ps = new PrintStream( out );
System.setErr(ps); //redirects stderr to the log file as well
} else {
return rtn;
}
InputSource source = new InputSource(new InputStreamReader(stream));
CSSOMParser parser = new CSSOMParser();
// parse and create a stylesheet composition
CSSStyleSheet stylesheet = parser.parseStyleSheet(source, null, null);
//ANY ERRORS IN THE DOM WILL BE SENT TO STDERR HERE!!
// now iterate through the dom and inspect.
CSSRuleList ruleList = stylesheet.getCssRules();
ps.println("Number of rules: " + ruleList.getLength());
for (int i = 0; i < ruleList.getLength(); i++)
{
CSSRule rule = ruleList.item(i);
if (rule instanceof CSSStyleRule)
{
CSSStyleRule styleRule=(CSSStyleRule)rule;
ps.println("selector:" + i + ": " + styleRule.getSelectorText());
CSSStyleDeclaration styleDeclaration = styleRule.getStyle();
for (int j = 0; j < styleDeclaration.getLength(); j++)
{
String property = styleDeclaration.item(j);
ps.println("property: " + property);
ps.println("value: " + styleDeclaration.getPropertyCSSValue(property).getCssText());
ps.println("priority: " + styleDeclaration.getPropertyPriority(property));
}
}// end of StyleRule instance test
} // end of ruleList loop
if (out != null) out.close();
if (stream != null) stream.close();
rtn = true;
}
catch (IOException ioe)
{
System.err.println ("IO Error: " + ioe);
}
catch (Exception e)
{
System.err.println ("Error: " + e);
}
finally
{
if (ps != null) ps.close();
}
return rtn;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)