Java 中的 CSS 解析器选项
简介
经常在 Java 中寻求 CSS 解析器的开发人员遇到从 HTML 元素中提取样式的挑战。虽然 W3C SAC 接口提供了基础,但查找全面的文档可能很困难。下面是对潜在解决方案的探索和指导您的详细代码示例。
探索 CSS 解析器选项
一个值得注意的选项是 CSSParser。它的错误反馈功能很有价值,这里有一个修改后的代码示例供您参考:
<code class="java">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.*; // Main class public class CSSParserTest { public static void main(String[] args) { CSSParserTest 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 { // Access CSS file as a resource InputStream stream = oParser.getClass().getResourceAsStream(cssfile); // Create log file out = new FileOutputStream("log.txt"); if (out != null) { ps = new PrintStream(out); System.setErr(ps); // Redirect stderr to log file } else { return rtn; } // Parse CSS file InputSource source = new InputSource(new InputStreamReader(stream)); CSSOMParser parser = new CSSOMParser(); CSSStyleSheet stylesheet = parser.parseStyleSheet(source, null, null); // Inspect CSS DOM 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)); } } } 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; } }</code>
测试 CSS 解析器
要测试解析器,请放置一个 CSS在源目录中创建名为“design.css”的文件并运行 CSSParserTest 的 main 方法。输出将记录到“log.txt”并包含有关 CSS 规则和样式的详细信息。
以上是如何选择 Java 中最好的 CSS 解析器?的详细内容。更多信息请关注PHP中文网其他相关文章!