简体   繁体   中英

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?

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM