tags:

views:

1317

answers:

2

Hi,

I'm looking for a CSS Parser in java. In particular my requirement is, for a given node/element in an HTML document, to be able to ask/get the css styles for that element from the Parser.

I know there is the W3C SAC interface and one or 2 implementations based on this - but turorials/examples appear non-existant.

Any help/points in rigth direction much appreciated.

Thanks

+1  A: 

an addition to cssparser.sourcefourge.net,

Cobra:

http://lobobrowser.org/cobra.jsp

Juraj Blahunka
great thanks i'll check it out
Richard
+1  A: 

I've used CSSParser and I like it- it gives good feedback on errors as well.

Here's some sample code I've found and modified:

package com.dlogic;

import com.steadystate.css.parser.CSSOMParser;
import org.w3c.css.sac.InputSource;
import org.w3c.dom.css.CSSStyleSheet;
import org.w3c.dom.css.CSSRuleList;
import org.w3c.dom.css.CSSRule;
import org.w3c.dom.css.CSSStyleRule;
import org.w3c.dom.css.CSSStyleDeclaration;
import java.io.*;


public class CSSParserTest 
{

    protected static CSSParserTest oParser;

    public static void main(String[] args) {

            oParser = new CSSParserTest();

            if (oParser.Parse("design.css")) {

                System.out.println("Parsing completed OK");

            } else {

                System.out.println("Unable to parse CSS");

            }   
    }


     public boolean Parse(String cssfile) 
     {

         FileOutputStream out = null; 
         PrintStream ps = null; 
         boolean rtn = false;

         try
         {

                // cssfile accessed as a resource, so must be in the pkg (in src dir).
                InputStream stream = oParser.getClass().getResourceAsStream(cssfile);

                 // overwrites and existing file contents
                 out = new FileOutputStream("log.txt");

                 if (out != null)
                 {
                     //log file
                     ps = new PrintStream( out );
                     System.setErr(ps); //redirects stderr to the log file as well

                 } else {

                     return rtn; 

                }


                InputSource source = new InputSource(new InputStreamReader(stream));
                CSSOMParser parser = new CSSOMParser();
                // parse and create a stylesheet composition
                CSSStyleSheet stylesheet = parser.parseStyleSheet(source, null, null);

                //ANY ERRORS IN THE DOM WILL BE SENT TO STDERR HERE!!
                // now iterate through the dom and inspect.

                CSSRuleList ruleList = stylesheet.getCssRules();

                ps.println("Number of rules: " + ruleList.getLength());


               for (int i = 0; i < ruleList.getLength(); i++) 
               {
                 CSSRule rule = ruleList.item(i);
                 if (rule instanceof CSSStyleRule) 
                 {
                     CSSStyleRule styleRule=(CSSStyleRule)rule;
                     ps.println("selector:" + i + ": " + styleRule.getSelectorText());
                     CSSStyleDeclaration styleDeclaration = styleRule.getStyle();


                     for (int j = 0; j < styleDeclaration.getLength(); j++) 
                     {
                          String property = styleDeclaration.item(j);
                          ps.println("property: " + property);
                          ps.println("value: " + styleDeclaration.getPropertyCSSValue(property).getCssText());
                          ps.println("priority: " + styleDeclaration.getPropertyPriority(property));   
                     }



                  }// end of StyleRule instance test
                } // end of ruleList loop

               if (out != null) out.close();
               if (stream != null) stream.close();
               rtn = true;
            }
            catch (IOException ioe)
            {
                System.err.println ("IO Error: " + ioe);
            }
            catch (Exception e)
            {
                System.err.println ("Error: " + e);

            }
            finally
            {
                if (ps != null) ps.close(); 
            }

            return rtn;

    }

}
Gene M.
Hi Gene, thanks for the info. I've been using CSSParser with not too many problems - except two small annoyances: 1) If there is an unrecognised or badly formatted rule the parser seems to barf on the whole file - as opposed to just dropping that 1 rule. Obviously with real-word css this happens quite a lot. Also, i think there is a bug with comments: multi-line comments seem to result in all subsequent css being dropped upto the next comment. have you noticed this?
Richard
Hi Richard, I've just started using CSSParser. I haven't noticed the dropped comments issue yet- I'm trying to find a <a href="http://stackoverflow.com/questions/1853379/parsing-css-with-java">solution</a> to the issue that it removes IE hacks, at the moment.Have you any experience with this issue yourself?
Gene M.
not really - although could be the reason for some of the barfing i see. Without knowing what you're doing exactly, I would suggest doing some pre-processing on each css file before parsing. You could maybe set up some regexes for IE hacks and strip them out?
Richard