javacssparsingcss-parsing

CSS parser parsing string content


I am trying to use CSS Parser in a java project to extract the CSS rules/DOM from a String of the text input.

All the examples that I have come across take the css file as input. Is there a way to bypass the file reading and work with the string content of the css file directly.

Because the class that I am working on gets only the string content of the css file and all the reading has already been taken care of.

Right now I have this, where the 'cssfile' is the filepath for css file being parsed.

InputStream stream = oParser.getClass().getResourceAsStream(cssfile);
InputSource source = new InputSource(new InputStreamReader(stream));
CSSOMParser parser = new CSSOMParser();
CSSStyleSheet stylesheet = parser.parseStyleSheet(source, null, null);
CSSRuleList ruleList = stylesheet.getCssRules();  
System.out.println("Number of rules: " + ruleList.getLength());

Reference link


Solution

  • A workaround that I found was to create a Reader using a StringReader with the contents and set the characterStream for the Input source. But there should be a better way to do this..

    InputSource inputSource = new InputSource();
    Reader characterStream = new StringReader(cssContent);
    inputSource.setCharacterStream(characterStream);
    CSSStyleSheet stylesheet = cssParserObj.parseStyleSheet(source, null,
                null);
    CSSRuleList ruleList = stylesheet.getCssRules();