2013-06-05 61 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文档。