Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Parser in Java [closed]

Tags:

java

css

parsing

Is there anything like Jsoup but instead of parsing HTML, I need to parse CSS, is there a parser similar to that that will create a Document model of a CSS? That perhaps can be used to iterate to nodes?

What I need to do is to find and replace "url" in the CSS file. And with html this is quite easy with Jsoup. However I am not sure if this will be possible with CSS.

If there are no such parser exist what are the options?

like image 242
quarks Avatar asked Jun 28 '26 10:06

quarks


2 Answers

Perhaps this might help you?

like image 101
Taymon Avatar answered Jun 30 '26 01:06

Taymon


I just rolled out my own CSS Stream Parser for Java, available on github. What sets this parser apart includes:

  • It is a stream parser, so the parser handler will receive notification of all new content immediately after each item has been parsed
  • Full support for all currently-documented At-Rules
  • Custom classes TokenSequence and Token simplify processes for handling selectors, etc.
  • Easy to use and to understand
  • Useful for validation or for more advanced applications
  • Scalable: designed to be able to handle changes to CSS definitions.

For your problem, just use the basic parsing technique:

try
{
    //First get the input stream. For example, from a file
    InputStream is = new FileInputStream(new File("/path/to/my/CSS/main.css"));

    //Then parse        
    CSSParser parser = new CSSParser(is, new DefaultCSSHandler());
    parser.parse();
}
catch (Throwable t)
{
    t.printStackTrace();
}

but override some methods in DefaultCSSHandler to look for the identifier you need.

like image 37
Phil Avatar answered Jun 29 '26 23:06

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!