3

I have this requirement that I need to replace URL in CSS, so far I have this code that display the rules of a css file:

@Override
public void parse(String document) {
    log.info("Parsing CSS: " + document);
    this.document = document;
    InputSource source = new InputSource(new StringReader(this.document));
    try {
        CSSStyleSheet stylesheet = parser.parseStyleSheet(source, null, null);
        CSSRuleList ruleList = stylesheet.getCssRules(); 
        log.info("Number of rules: " + ruleList.getLength());
        // lets examine the stylesheet contents 
        for (int i = 0; i < ruleList.getLength(); i++) 
        { 
            CSSRule rule = ruleList.item(i); 
            if (rule instanceof CSSStyleRule) { 
                CSSStyleRule styleRule=(CSSStyleRule)rule; 
                log.info("selector: " + styleRule.getSelectorText()); 
                CSSStyleDeclaration styleDeclaration = styleRule.getStyle(); 
                //assertEquals(1, styleDeclaration.getLength()); 
                for (int j = 0; j < styleDeclaration.getLength(); j++) {
                    String property = styleDeclaration.item(j); 
                    log.info("property: " + property); 
                    log.info("value: " + styleDeclaration.getPropertyCSSValue(property).getCssText()); 
                    } 
                } 
            } 
    } catch (IOException e) {
        e.printStackTrace();
    }

}

However, I am not sure whether how to actually replace the URL since there is not much a documentation about CSS Parser

3
  • What exactly do you want to replace? Is there a specific URL string you want to put in place of every URL? Or do you want to replace some part of every URL in the CSS ? Commented Apr 6, 2012 at 14:36
  • I need to replace part of the URL Commented Apr 7, 2012 at 15:41
  • just curious: to which API do CSSRuleList, CSSRule and CSSStyleSheet belong? Commented Sep 22, 2012 at 18:04

1 Answer 1

1

Here is the modified for loop:

//Only images can be there in CSS.
Pattern URL_PATTERN = Pattern.compile("http://.*?jpg|jpeg|png|gif");
for (int j = 0; j < styleDeclaration.getLength(); j++) {
    String property = styleDeclaration.item(j); 
    String value = styleDeclaration.getPropertyCSSValue(property).getCssText();

    Matcher m = URL_PATTERN.matcher(value);
    //CSS property can have multiple URL. Hence do it in while loop.
    while(m.find()) {
        String originalUrl = m.group(0);
       //Now you've the original URL here. Change it however ou want.
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.