jStyleParser
jStyleParser is a Java library for parsing CSS style sheets and assigning styles to the HTML or XML document elements according to the CSS 3 specifications.
It allows parsing the individual CSS files as well as computing the efficient style of the DOM elements.
See the project page for more information:
http://cssbox.sourceforge.net/jstyleparser
Installation
With Maven, use the following dependency:
<dependency>
<groupId>net.sf.cssbox</groupId>
<artifactId>jstyleparser</artifactId>
<version>4.0.0</version>
</dependency>
Parsing CSS
The basic CSSFactory
interface provides functions parsing CSS strings, files or URLs. The parsed style sheet
is represented by the corresponding data structures that allow accessing all parts of the style sheet
in a type-safe way.
String css = "div { background-color: red; width: 12px; }";
StyleSheet sheet = CSSFactory.parseString(css, new URL("http://base.url"));
RuleSet rule = (RuleSet) sheet.get(0);
CombinedSelector selector = rule.getSelectors()[0];
Declaration bgDecl = rule.get(0);
String bgProperty = bgDecl.getProperty();
TermColor color = (TermColor) bgDecl.get(0);
System.out.println(selector);
System.out.println(bgProperty);
System.out.println(color);
System.out.println(sheet);
See the details in the documentation.
Computing style for DOM elements
jStyleParser allows to map the style rules to the individual elements in a DOM tree based on their selectors. This allows
obtaining the exact style for any HTML element.
org.w3c.dom.Document doc = ...
MediaSpec media = new MediaSpecAll();
StyleMap map = CSSFactory.assignDOM(doc, "UTF-8", new URL("https://base.url/"), media, true);
Element div = doc.getElementById("searchelement");
NodeData style = map.get(div);
CSSProperty.Margin mm = style.getProperty("margin-top");
System.out.println("margin-top=" + mm);
if (mm == Margin.length) {
TermLength mtop = style.getValue(TermLength.class, "margin-top");
System.out.println("value=" + mtop);
}
Multi-value properties
Some properties (e.g. background
) allow multiple values. In that case, the NodeData
interface
includes the getListSize()
method for getting the number of values specified and the getProperty()
and getValue()
functions with an index argument:
Element div = doc.getElementById("searchelement");
NodeData style = map.get(div);
int bgcnt = style.getListSize("background-image", true);
for (int index = 0; index < bgcnt; index++>) {
CSSProperty.BackgroundImage image = style.getProperty("background-image", index);
if (image == CSSProperty.BackgroundImage.uri) {
TermURI urlstring = style.getValue(TermURI.class, "background-image", index);
}
}
See the details in the documentation.
License
All the source code of jStyleParser itself is licensed under the GNU Lesser General
Public License (LGPL), version 3. A copy of the LGPL can be found
in the LICENSE file.