2009-10-03 62 views
28

我正在尋找java中的CSS解析器。特別是我的要求是,對於HTML文檔中給定的節點/元素,能夠從解析器中獲取/獲取該元素的CSS樣式。在java中尋找CSS解析器

我知道有W3C SAC接口和基於此的一個或兩個實現 - 但turorials /示例顯示不存在。

任何幫助/點在正確的方向非常讚賞。

感謝

+5

看看 - http://cssparser.sourceforge.net/ – adatapost 2009-10-03 12:43:54

+1

@adatapost:重新發布您的回覆爲「答案」,而不是「意見」 – 2009-10-05 04:38:38

回答

4

的除了cssparser.sourcefourge.net,

眼鏡蛇:

http://lobobrowser.org/cobra.jsp

+0

十分感謝,我會檢查出來 – 2009-10-11 14:21:12

+0

還採用舊CSSParser項目 – 2011-08-11 12:56:23

16

我用CSSParser,我喜歡它 - 它給出了錯誤的反饋良好好。

下面是一些示例代碼,我發現和修改:

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; 

    } 

} 
+0

嗨基因,感謝您的信息。我一直在使用CSSParser,但沒有太多的問題 - 除了兩個小問題:1)如果存在一個無法識別或格式不正確的規則,解析器似乎在整個文件上都會出現漏洞,而不是放棄這條規則。很明顯,用真正的css這個發生了很多。另外,我認爲有一條評論錯誤:多行註釋似乎導致所有後續的css被放棄到下一個評論。你有沒有注意到這個? – 2009-12-07 10:35:37

+0

嗨理查德,我剛開始使用CSSParser。我還沒有注意到這個掉線的評論問題,我正試圖找到一個solution來解決目前它消除IE黑客的問題。 你對這個問題有什麼經驗嗎? – 2009-12-07 11:22:02

+0

不是真的 - 雖然可能是我看到一些barfing的原因。不知道你在做什麼,我會建議在解析之前對每個css文件進行一些預處理。你可以爲IE黑客設置一些正則表達式並將它們去掉? – 2009-12-07 11:36:59

11

我需要一個CSS解析器爲自己的項目,但我發現「CSSParser」過於乏味和僵化(但可能只是我),所以我最終編寫了我自己的簡單但功能豐富的CSS解析器。

隨意使用它,如果你想:-)

OSBCP CSS Parser

+0

我很快查看了你的項目,看起來你的解析器功能非常強大。我正在認真考慮在我的一個項目中使用它。我需要了解哪些問題?另外,CSS規則可以在內存中修改,然後再次保存到CSS文件中?謝謝。 – stepanian 2012-03-19 21:57:24

+0

是的。它將規則解析成規則列表,可以修改規則列表,然後使用toString()寫回到字符串/文件。我希望能回答你的問題。 – corgrath 2012-04-01 18:48:33

+0

謝謝。我正在使用它,它對我來說非常合適。 – stepanian 2012-04-11 00:32:39

13

一個CSS庫,用於讀取和寫入CSS2和CSS3文件Java是PH-CSShttps://github.com/phax/ph-css 它是基於在JavaCC語法中,同時支持CSS2和CSS3,另外還可以解析HTML樣式屬性。

  • 它支持最常見的黑客「*」,「_」和「$」未遵循規範的
  • 它支持CSS的數學 - 的計算()表達
  • 它支持@page規則
  • 它支持CSS3媒體查詢
  • 它支持@viewport規則
  • 它支持@keyframes規則
  • 它支持@supports規則 - 很新
  • 它支持@namespace規則
  • 你可以得到不同的元素(起始和終止行+列數 - 既爲標籤以及爲完整的結構)源位置信息

由於2013年5月21日JDK 1。5版本也是可用的,這使得它對於Android開發更有趣

+1

我確實使用了它,並且自問題被問到,它確實演變得很好。 Nice API,訪問者只需獲取所需的元素,只是缺少一些文檔(但API文檔相當不錯)。推薦的。 – Martin 2013-04-22 12:18:04

+0

這個好項目的文檔很差,這太浪費了。通過一點工作,這可能會變成一個更受歡迎的項目。 – Gili 2014-03-08 06:05:22

+0

這看起來像是我最好的一個 – 2016-06-21 23:53:56

1

jStyleParser正好提供了這個功能。它解析所有引用的樣式表並將它們映射到DOM樹節點。

1

如果用CSSParser掙扎,因爲似乎沒有文檔的一切,你也許想分析只是一個CSS字符串,如從風格的參數值,這裏是我使用的簡單示例:

import org.junit.Test; 
import org.w3c.css.sac.InputSource; 
import org.w3c.dom.css.CSSRule; 
import org.w3c.dom.css.CSSStyleDeclaration; 
import org.w3c.dom.css.CSSValue; 

import com.steadystate.css.parser.CSSOMParser; 

public class ParseCssTest { 

@Test 
public void testParseStyleDeclaration() throws IOException { 
    String cssSample = "margin-top: 0cm; margin-bottom: 0cm; background: #e6e6e6"; 
    CSSOMParser parser = new CSSOMParser(); 
    CSSStyleDeclaration o = parser.parseStyleDeclaration(new InputSource(new StringReader(cssSample))); 
    assertEquals("margin-top: 0cm; margin-bottom: 0cm; background: rgb(230, 230, 230)", o.toString()); 
    assertEquals("0cm", o.getPropertyCSSValue("margin-bottom").toString()); 
    assertEquals("0cm", o.getPropertyCSSValue("margin-bottom").getCssText()); 
    assertEquals(null, o.getPropertyCSSValue("foo")); 
} 

@Test 
public void testParseARule() throws IOException { 
    String cssSample = "r1 { margin-top: 0cm; margin-bottom: 0cm; background: #e6e6e6 }"; 
    CSSOMParser parser = new CSSOMParser(); 
    CSSRule o = parser.parseRule(new InputSource(new StringReader(cssSample))); 
    assertEquals("r1 { margin-top: 0cm; margin-bottom: 0cm; background: rgb(230, 230, 230) }", o.toString()); 
} 

@Test 
public void parseStyleDeclarationWithAdvancedTests() throws IOException { 
    String cssSample = "margin-top: 0 cm; margin-bottom: 0cm; background: #e6e6e6"; 
    CSSOMParser parser = new CSSOMParser(); 
    CSSStyleDeclaration o = parser.parseStyleDeclaration(new InputSource(new StringReader(cssSample))); 
    assertEquals("margin-top: 0 cm; margin-bottom: 0cm; background: rgb(230, 230, 230)", o.toString()); 

    assertEquals("0cm", o.getPropertyCSSValue("margin-bottom").toString()); 
    assertEquals("0cm", o.getPropertyCSSValue("margin-bottom").getCssText()); 
    assertEquals(CSSValue.CSS_VALUE_LIST, o.getPropertyCSSValue("margin-top").getCssValueType()); 

    assertEquals("0 cm", o.getPropertyCSSValue("margin-top").toString()); 
    assertEquals("0 cm", o.getPropertyCSSValue("margin-top").getCssText()); 
    assertEquals(CSSValue.CSS_VALUE_LIST, o.getPropertyCSSValue("margin-top").getCssValueType()); 
} 
} 

CSSParser的巨大優勢在於它目前在Maven中。所以,如果你尋找一些相當簡單和直接可用的CSSParser似乎是不錯的選擇。

注意:它會自動將顏色從十六進制格式轉換爲rgb()格式,但不提供單位大小的幫助,它將它們視爲值列表!不太好。

1

我剛推出了我自己的CSS Stream Parser for Java,可在github上找到。是什麼使這個解析器除了包括:

  • 它是一種流解析器,所以解析器處理器將接收後立即每個項目已經被解析爲所有當前記錄在規則
  • 全面支持所有新內容的通知
  • 自定義類TokenSequence和處理選擇Token簡化流程等
  • 易於使用和理解
  • 有用的驗證或更高級的應用
  • 可伸縮:設計用於處理對CSS定義的更改。