2013-06-05 164 views
0

所以我有一個JEditorPane來顯示一個HTML頁面。我已經編寫了用於通過id檢索HTML元素的代碼。我無法獲得它們的屬性。JEditorPane:獲取HTML元素的類屬性

例如,在HTML頁面中有<span id="0" class="insert">abc</span>。考慮到它的ID,我想獲得類名insert

我的代碼看起來像這樣,

HTMLDocument html = (HTMLDocument) jeditor.getDocument(); 
    String id = "0"; 

    // make sure this id exists 
    if ((elem = html.getElement(id)) != null) { 
     // get the name of class in span element 
     String className = (String) elem.getAttributes().getAttribute("class"); 
     ... 
    } 

這是行不通的。然而,elem.getAttributes()返回以下內容,

LeafElement(content) 15,16 

這不像HTML元素的一組屬性。我應該如何獲得HTML元素的類屬性?

謝謝!

+0

我已經給出了這個。我不應該浪費我的時間來從Java中獲取HTML類的屬性。 –

回答

1

我認爲問題在於您傳遞給getAttribute方法的參數。而不是字符串「類」,您必須使用HTML.Attribute.CLASS。所以,在最後一行代碼將改爲:

String className = (String) elem.getAttributes() 
           .getAttribute(HTML.Attribute.CLASS); 

類似的問題:How do I retrieve the attribute of an element using Swing's HTMLEditorKit.ParserCallback?

在您需要處理其他屬性的情況下,看看還在爲HTML.Attribute class的API文檔。