在 Java 中寻找 CSS 解析器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1513587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looking for a CSS Parser in java
提问by Richard H
I'm looking for a CSS Parser in java. In particular my requirement is, for a given node/element in an HTML document, to be able to ask/get the css styles for that element from the Parser.
我正在寻找 Java 中的 CSS 解析器。特别是我的要求是,对于 HTML 文档中的给定节点/元素,能够从解析器询问/获取该元素的 css 样式。
I know there is the W3C SAC interface and one or 2 implementations based on this - but turorials/examples appear non-existant.
我知道有 W3C SAC 接口和基于此的一两个实现 - 但 turorials/examples 似乎不存在。
Any help/points in right direction much appreciated.
任何帮助/指向正确方向的点都非常感谢。
Thanks
谢谢
回答by Juraj Blahunka
an addition to cssparser.sourcefourge.net,
cssparser.sourcefourge.net 的补充,
Cobra:
眼镜蛇:
回答by Gene Myers
I've used CSSParserand I like it- it gives good feedback on errors as well.
我使用过CSSParser并且我喜欢它 - 它也对错误提供了很好的反馈。
Here's some sample code I've found and modified:
这是我找到并修改的一些示例代码:
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;
}
}
回答by Dmitry Negoda
Check out SAC and its implementstions here: http://www.w3.org/Style/CSS/SAC/
在此处查看 SAC 及其实现:http: //www.w3.org/Style/CSS/SAC/
CSSParser is a little bit out of date
CSSParser 有点过时了
回答by corgrath
I needed a CSS parser for an own project, but I found "CSSParser" to be too tedious and inflexible to work with (but that could have just been me), so I ended up writing my own simple but functional CSS parser.
我需要为自己的项目使用 CSS 解析器,但我发现使用“CSSParser”太乏味且不灵活(但我可能就是这样),因此我最终编写了自己的简单但功能强大的 CSS 解析器。
Feel free to use it if you want to :-)
如果您愿意,请随意使用它:-)
回答by Philip Helger
A CSS library for reading and writing CSS2 and CSS3 files in Java is ph-cssfrom https://github.com/phax/ph-cssIt is based on a JavaCC grammar and supports both CSS2 as well as CSS3 and additionally lets you parse HTML style attributes.
在Java读取和写入CSS2和CSS3文件CSS库是PH-CSS从https://github.com/phax/ph-css它是基于一个JavaCC的语法和支持CSS2和CSS3,另外可以让你解析 HTML 样式属性。
- It supports the most common hacks "*", "_" and "$" which are not spec compliant
- It supports CSS math - the calc() expression
- It supports the @page rule
- It supports the CSS3 media queries
- It supports @viewport rules
- It supports @keyframes rules
- It supports @supports rules - quite new
- It supports the @namespace rules
- You can get source location information for the different elements (line + column number for start and end - both for the tag as well as for the complete construct)
- 它支持最常见的不符合规范的黑客“*”、“_”和“$”
- 它支持 CSS 数学 - calc() 表达式
- 它支持@page 规则
- 它支持 CSS3 媒体查询
- 它支持@viewport 规则
- 它支持@keyframes 规则
- 它支持@supports 规则 - 相当新
- 它支持@namespace 规则
- 您可以获得不同元素的源位置信息(开始和结束的行 + 列号 - 标签以及完整构造)
Since May 21st, 2013 a JDK 1.5 version is also available, which makes it more interesting for Android development
自 2013 年 5 月 21 日起,JDK 1.5 版本也可用,这使得 Android 开发更有趣
回答by radkovo
jStyleParserprovides exactly this functionality. It parses all the referenced style sheets and maps them to the DOM tree nodes.
jStyleParser 恰好提供了此功能。它解析所有引用的样式表并将它们映射到 DOM 树节点。
回答by Espinosa
If you struggle with CSSParser, because there seems to be no documentation at all, and you perhaps want to parse just a CSS String, like value from style parameter, here is my simple sample of use:
如果您对 CSSParser 感到困惑,因为似乎根本没有文档,而且您可能只想解析一个 CSS 字符串,例如样式参数中的值,这是我的简单使用示例:
import org.junit.Test;
import org.w3c.css.sac.InputSource;
import org.w3c.dom.css.CSSRule;
import org.w3c.dom.css.CSSStyleDeclaration;
import org.w3c.dom.css.CSSValue;
import com.steadystate.css.parser.CSSOMParser;
public class ParseCssTest {
@Test
public void testParseStyleDeclaration() throws IOException {
String cssSample = "margin-top: 0cm; margin-bottom: 0cm; background: #e6e6e6";
CSSOMParser parser = new CSSOMParser();
CSSStyleDeclaration o = parser.parseStyleDeclaration(new InputSource(new StringReader(cssSample)));
assertEquals("margin-top: 0cm; margin-bottom: 0cm; background: rgb(230, 230, 230)", o.toString());
assertEquals("0cm", o.getPropertyCSSValue("margin-bottom").toString());
assertEquals("0cm", o.getPropertyCSSValue("margin-bottom").getCssText());
assertEquals(null, o.getPropertyCSSValue("foo"));
}
@Test
public void testParseARule() throws IOException {
String cssSample = "r1 { margin-top: 0cm; margin-bottom: 0cm; background: #e6e6e6 }";
CSSOMParser parser = new CSSOMParser();
CSSRule o = parser.parseRule(new InputSource(new StringReader(cssSample)));
assertEquals("r1 { margin-top: 0cm; margin-bottom: 0cm; background: rgb(230, 230, 230) }", o.toString());
}
@Test
public void parseStyleDeclarationWithAdvancedTests() throws IOException {
String cssSample = "margin-top: 0 cm; margin-bottom: 0cm; background: #e6e6e6";
CSSOMParser parser = new CSSOMParser();
CSSStyleDeclaration o = parser.parseStyleDeclaration(new InputSource(new StringReader(cssSample)));
assertEquals("margin-top: 0 cm; margin-bottom: 0cm; background: rgb(230, 230, 230)", o.toString());
assertEquals("0cm", o.getPropertyCSSValue("margin-bottom").toString());
assertEquals("0cm", o.getPropertyCSSValue("margin-bottom").getCssText());
assertEquals(CSSValue.CSS_VALUE_LIST, o.getPropertyCSSValue("margin-top").getCssValueType());
assertEquals("0 cm", o.getPropertyCSSValue("margin-top").toString());
assertEquals("0 cm", o.getPropertyCSSValue("margin-top").getCssText());
assertEquals(CSSValue.CSS_VALUE_LIST, o.getPropertyCSSValue("margin-top").getCssValueType());
}
}
Big advantage of CSSParser is that it is currently in Maven. So if you look for something rather simple and straightforwardly usable CSSParser seems to be good option.
CSSParser 的一大优势是它目前在 Maven 中。因此,如果您寻找一些相当简单且直接可用的 CSSParser 似乎是不错的选择。
Notes: it does automatic conversion for colors from hex format to rgb() format, but provides no help with sizes with units, it sees them as list of values! Not so good.
注意:它会自动将颜色从十六进制格式转换为 rgb() 格式,但不提供有关单位大小的帮助,它将它们视为值列表!不太好。
回答by Phil
I just rolled out my own CSS Stream Parser for Java, available on github. What sets this parser apart includes:
我刚刚推出了我自己的用于 Java 的 CSS Stream Parser,可在github 上获得。这个解析器与众不同的地方包括:
- It is a stream parser, so the parser handler will receive notification of all new content immediately after each item has been parsed
- Full support for all currently-documented At-Rules
- Custom classes
TokenSequence
andToken
simplify processes for handling selectors, etc. - Easy to use and to understand
- Useful for validation or for more advanced applications
- Scalable: designed to be able to handle changes to CSS definitions.
- 它是一个流解析器,因此解析器处理程序将在每个项目被解析后立即收到所有新内容的通知
- 完全支持所有当前记录的规则
- 自定义类
TokenSequence
并Token
简化处理选择器等的过程。 - 易于使用和理解
- 用于验证或更高级的应用程序
- 可扩展:旨在能够处理对 CSS 定义的更改。