开发者

How do I retrieve the attribute of an element using Swing's HTMLEditorKit.ParserCallback?

I am extending HTMLEditorKit.ParserCallback to parse HTML. I am matching on a certain element type in an overridden method like this:

@Override
public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {
    if (Tag.DIV.equals(t)) {
        String id = (String) a.getAttribute("id");
        String clazz = (String) a.getAttribute("clas开发者_如何转开发s");
        ...

After this line, id and clazz are always null, yet I know for a fact the element in question contains these attributes.

How should I retrieve these attributes?


The MutableAttributeSet uses a pre-Java 5 type-safe enum pattern to represent the key set. This means even though the attribute has the name "class", just inserting the String will not retrieve the value of the attribute. Instead, use:

@Override
public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {
    if (Tag.DIV.equals(t)) {
        String id = (String) a.getAttribute(HTML.Attribute.ID);
        String clazz = (String) a.getAttribute(HTML.Attribute.CLASS);
        ...

The HTML.Attribute class contains many more attributes which can be matched on.

(This confused me for a while and I didn't come across example of this usage when searching online).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜