2014-11-06 60 views
1

我有HTML格式的字符串,我試圖使用Jsoup獲取所有屬性及其值。在jsoup中獲取html字符串中的所有屬性

字符串是

String string= 
"<button class=submit btn primary-btn flex-table-btn js-submit type=submit>Sign in</button>"; 

Document doc = Jsoup.parse(string); 
    try { 
     org.jsoup.nodes.Attributes attrs = doc.attributes(); 

     for(org.jsoup.nodes.Element element : doc.getAllElements()) 
     { 
       for(Attribute attribute : element.attributes()) 
       { 
        System.out.println(attribute.getKey() + " --::-- "+attribute.getValue() ); 
       } 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

我期望的輸出是::

key: **class** , Value is: **submit btn primary-btn flex-table-btn js-submit** 

key: **type** , Value is: **submit** 

但我得到的是這種

key: class , Value is: submit key: btn , Value is: key: primary-btn , Value is: key: flex-table-btn , Value is: key: js-submit , Value is: key: type , Value is: submit

這是因爲引號的。如果我用

String string= 
"<button class='submit btn primary-btn flex-table-btn js-submit' type='submit'>  Sign in</button>"; 

我會得到我想要的輸出。但我試圖得到沒有引號。

回答

0

不能不帶引號,因爲引號不是可選的。如果沒有引號,那麼您引用的HTML描述了一個元素,其中包含一個類(submit)和一系列非類,無效的附加屬性,名稱如btnflex-table等,這就是瀏覽器將如何解釋它,就像JSoup所做的一樣。如果這些要素是要素上的附加類別,則需要要求

the specification

未引用屬性值的語法

屬性名稱,後面的零個或多個空格字符,接着是單獨的U + 003D等號字符,接着是零個或更多的空格字符,後面是屬性值,除了上面給出的屬性值的要求之外,不能包含任何字面空格字符,任何U + 0022 QUOTATIO (U + 003D)字符,「<」(U + 003C)字符,「>」(U + 003E)字符或U + 0060字符GRAVE ACCENT字符(`),並且不能是空字符串。

請注意,「一定不能包含任何文字空格字符」我強調的部分。

0

很簡單與Jsoup

Document doc = Jsoup.parse(HTML); 
List<String> tags = new ArrayList<String>(); //record tags 

for(Element e : doc.getAllElements()){  // all elements in html 

    tags.add(e.tagName().toLowerCase()); // add each tag in tags List 
    //System.out.println("Tag: "+ e.tag()+" attributes = "+e.attributes()); // attributes with values in string 
    //System.out.println("Tag: "+ e.tag()+" attributes = "+e.attributes().asList()); //attributes in List<Attribute> 

    for(Attribute att : e.attributes().asList()){ // for each tag get all attributes in one List<Attribute> 
     System.out.print("Key: "+att.getKey()+ " , Value: "+att.getValue()); 
     System.out.println(); 
    } 
} 

System.out.println("*****************"); 
System.out.println("All Tags = "+tags); 
System.out.println("Distinct Tags = "+ new HashSet<String>(tags));