在java中使用htmleditorkit查询html文件时出现问题

kupeojn6  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(259)

my html包含以下形式的标记:

<div class="author"><a href="/user/1" title="View user profile.">Apple</a> - October 22, 2009 - 01:07</div>

我想从每个标签中提取日期,在本例中为“2009年10月22日-01:07”
我实现了javax.swing.text.html.htmleditorkit.parsercallback,如下所示:

class HTMLParseListerInner extends HTMLEditorKit.ParserCallback {   
    private ArrayList<String> foundDates = new ArrayList<String>();
    private boolean isDivLink = false;

    public void handleText(char[] data, int pos) {
        if(isDivLink)
            foundDates.add(new String(data)); // Extracts "Apple" instead of the date.
    }

    public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {       
        String divValue = (String)a.getAttribute(HTML.Attribute.CLASS);
        if (t.toString() == "div" && divValue != null && divValue.equals("author"))
            isDivLink = true;
    }
}

但是,上面的解析器返回“apple”,它位于标记内的超链接中。如何修复解析器以提取日期?

a8jjtwal

a8jjtwal1#

覆盖 handleEndTag 并检查 "a" ?
然而,这个html解析器来自90年代早期,并且这些方法没有很好地指定。

fkaflof6

fkaflof62#

import java.io.*;
import java.util.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;

public class ParserCallbackDiv extends HTMLEditorKit.ParserCallback
{
    private boolean isDivLink = false;
    private String divText;

    public void handleEndTag(HTML.Tag tag, int pos)
    {
        if (tag.equals(HTML.Tag.DIV))
        {
            System.out.println( divText );
            isDivLink = false;
        }
    }

    public void handleStartTag(HTML.Tag tag, MutableAttributeSet a, int pos)
    {
        if (tag.equals(HTML.Tag.DIV))
        {
            String divValue = (String)a.getAttribute(HTML.Attribute.CLASS);

            if ("author".equals(divValue))
                isDivLink = true;
        }
    }

    public void handleText(char[] data, int pos)
    {
        divText = new String(data);
    }

    public static void main(String[] args)
    throws IOException
    {
        String file = "<div class=\"author\"><a href=\"/user/1\"" +
            "title=\"View user profile.\">Apple</a> - October 22, 2009 - 01:07</div>";
        StringReader reader = new StringReader(file);

        ParserCallbackDiv parser = new ParserCallbackDiv();

        try
        {
            new ParserDelegator().parse(reader, parser, true);
        }
        catch (IOException e)
        {
            System.out.println(e);
        }
    }
}

相关问题