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:
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.
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.