【问题标题】:JEditorPane: get class attribute of HTML elementJEdi​​torPane:获取 HTML 元素的类属性
【发布时间】:2013-11-11 04:06:07
【问题描述】:

所以我有一个 JEditorPane 来显示 HTML 页面。我编写了代码来通过 id 检索 HTML 元素。我无法获取它们的属性。

例如,HTML 页面中有<span id="0" class="insert">abc</span>。我想得到类名insert,给定它的id。

我的代码是这样的,

    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 元素的 class 属性?

谢谢!

【问题讨论】:

  • 我已经放弃了。我不应该浪费生命从 Java 中的 HTML 获取类属性。

标签: java html swing jeditorpane htmleditorkit


【解决方案1】:

我认为问题在于您传递给 getAttribute 方法的参数。您必须使用 HTML.Attribute.CLASS 而不是字符串 "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 文档。

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2011-08-20
    • 2012-07-29
    • 2012-02-21
    • 1970-01-01
    • 2012-03-14
    相关资源
    最近更新 更多