我正在扩展 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 始终为 null,但我确实知道所讨论的元素包含这些属性。
我应该如何检索这些属性?
最佳答案
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 类包含更多可以匹配的属性。
(这让我困惑了一段时间,在网上搜索时我没有遇到这种用法的例子)。
关于java - 如何使用 Swing 的 HTMLEditorKit.ParserCallback 检索元素的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1767135/