2012-04-02 17 views
3

我有這樣的要求,我需要替換CSS網址,到目前爲止,我有這樣的代碼,顯示一個CSS文件的規則:在CSS用CSS解析器和正則表達式(Java)的更換網址

@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(); 
    } 

} 

不過,我不知道是否如何真正更換URL,因爲沒有太大的文檔有關CSS Parser

+0

你到底要什麼來替代?是否有一個特定的URL字符串要代替每個URL? 或者你想替換CSS中每個URL的一部分? – 2012-04-06 14:36:23

+0

我需要替換部分URL – xybrek 2012-04-07 15:41:46

+0

只是好奇:CSSRuleList,CSSRule和CSSStyleSheet屬於哪個API? – amphibient 2012-09-22 18:04:38

回答

1

下面是修改for循環:

//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. 
    } 
}