如何使用Swing的HTMLEditorKit.ParserCallback检索元素的属性? [英] How do I retrieve the attribute of an element using Swing's HTMLEditorKit.ParserCallback?

查看:457
本文介绍了如何使用Swing的HTMLEditorKit.ParserCallback检索元素的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在扩展HTMLEditorKit.ParserCallback来解析HTML。

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

在这行之后,id和clazz总是空,但我知道因为这个问题中的元素包含了这些属性。



我应该如何检索这些属性?

解决方案

MutableAttributeSet使用Java 5之前的类型安全枚举模式来表示键集。这意味着即使该属性具有名称class,只是插入String将不会检索该属性的值。相反,使用:

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

HTML.Attribute类包含许多可以匹配的属性。 b
$ b

(这让我困惑了一阵子,在网上搜索时我没有遇到这种用法的例子)。


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?

解决方案

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

这篇关于如何使用Swing的HTMLEditorKit.ParserCallback检索元素的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆