Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing CSS with jSoup

I am trying to parse CSS DOM in Java and am already using jSoup for the same function for HTML. I was looking through the jSoup API (as well as Google, of course) but didn't find any CSS-related parsing classes. Is there a way to parse the CSS format into a DOM using jSoup or do I need a different API?

like image 495
amphibient Avatar asked Mar 23 '13 21:03

amphibient


1 Answers

Jsoup cannot traverse the CSS DOM, although you can access it by selecting on the style/link tags.

Take a look at CSS Parser, it looks very promising.

    InputSource source = new InputSource(
        new StringReader(
            "h1 { background: #ffcc44; } div { color: red; }"));
    CSSOMParser parser = new CSSOMParser(new SACParserCSS3());
    CSSStyleSheet sheet = parser.parseStyleSheet(source, null, null);
    CSSRuleList rules = sheet.getCssRules();
    for (int i = 0; i < rules.getLength(); i++) {
        final CSSRule rule = rules.item(i);
        System.out.println(rule.getCssText());
    }

Output

h1 { background: rgb(255, 204, 68) }
div { color: red }
like image 111
Zack Avatar answered Sep 21 '22 11:09

Zack