开发者

HTML ParserDelegator and ParserCallback not working

开发者 https://www.devze.com 2023-03-17 08:38 出处:网络
so what I\'m trying to do is pretty simple. I\'m parsing an HTML document for script tags, using the ParserDelegator, and using a ParserCallback to spit out the script tags. But when I run this progra

so what I'm trying to do is pretty simple. I'm parsing an HTML document for script tags, using the ParserDelegator, and using a ParserCallback to spit out the script tags. But when I run this program, it does nothing. The callbacks are never called. My html file path is correct and it does contain script tags. It's formatted correctly too.

import java.io.*;
import javax.swing.text.html.parser.ParserDelegator;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.HTML;
import javax.swing.text.SimpleAttributeSet;
import java.util.Enumeration;

public class JSFinder {
    //static ParserDelegator pd;
    public JSFinder () {
        //pd = new ParserDelegator();
    }

    public static void main(String args[]) {
        try {
            HTMLEditorKit.ParserCallback callback = new ScriptTagCallBack();
            new ParserDelegator().parse(new InputStreamReader(new FileInputStream(new File ("<path-to-html>"))), callback, false);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class ScriptTagCallBack extends HTMLEditorKit.ParserCallback {
    public ScriptTagCallBack() {
        super();
    }
    public void handleStartTag(HTML.Tag t, SimpleAttributeSet a, int pos) {
        if(t == HTML.Tag.SCRIPT) {
            System.out.println("Found a script tag");
            System.out.println(a);
        }
        else {
            System.out.println("Not a script tag");
        }
    }
    public void handleEndTag(HTML.Tag t, SimpleAttributeSet a, int pos) {
        if(t == HTML.Tag.SCRIPT) {
            System.out.println("Found a script tag");
            System.out.println(a);
        }
        else {
            System.out.println("Not a script tag");
        }
    }
}

Any idea what I'm doing wrong? I've looked at examples (like this one: http://www.java2s.com/Tutorial/Java/0320__Network/HTMLparserbasedonHTMLEditorKitParserCallback.htm) and I'm doing basically the same thing (except maybe that I 开发者_StackOverflow社区haven't overridden all the methods of ParserCallback and I'm using a file path instead of a URL). Thanks in advance.


Use the @Override annotation to see that you are hiding rather than overriding methods of HTMLEditorKit.ParserCallback. Fix the signatures, and it works.

0

精彩评论

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

关注公众号