0

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

Community
  • 1
  • 1

1 Answers1

0

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();
  • Why should there be a better way? This seems like a perfectly legitimate way to do it. – Mike Samuel Aug 21 '14 at 18:20
  • I was searching in the CSS Parser api's for a way to directly feed the string content to get a CSSStyleSheet. Wanted to do away with the creation of a Reader object from the String.. Failing which I would go with the above solution itself.. – Samarth Asthana Aug 21 '14 at 19:23
  • `StringReader` is a pretty standard adapter between `String` and `Reader` based APIs. Making your APIs take a `Reader` or a `Readable` enables both content in-memory and from an external resource, while keeping the API small, and without introducing ambiguity about whether a string input is a file path, URL, or the content itself. – Mike Samuel Aug 21 '14 at 19:44
  • Oh never thought about it that way!! Make sense to separate url input from string content input from an API's perspective. Thanks!! – Samarth Asthana Aug 21 '14 at 19:56