tags:

views:

17

answers:

1

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("class");
        ...

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?

+1  A: 

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).

Grundlefleck