java - 为什么 Swing Parser 的 handleText 不处理嵌套标签?

标签 java html html-parsing escaping htmleditorkit

我需要转换一些具有嵌套标签的 HTML 文本,以用 css 属性装饰“matches”以突出显示它(如 firefox 搜索)。 我不能只进行简单的替换(例如,假设用户搜索“img”),因此我尝试仅在正文文本中进行替换(而不是在标签属性上)。

我有一个非常简单的 HTML 解析器,我认为应该这样做:

final Pattern pat = Pattern.compile(srch, Pattern.CASE_INSENSITIVE);
Matcher m = pat.matcher(output);
if (m.find()) {
    final StringBuffer ret = new StringBuffer(output.length()+100);
    lastPos=0;
    try {
        new ParserDelegator().parse(new StringReader(output.toString()),
        new HTMLEditorKit.ParserCallback () {
            public void handleText(char[] data, int pos) {
                ret.append(output.subSequence(lastPos, pos));
                Matcher m = pat.matcher(new String(data));
                ret.append(m.replaceAll("<span class=\"search\">$0</span>"));
                lastPos=pos+data.length;
            }
        }, false);
        ret.append(output.subSequence(lastPos, output.length()));
        return ret;
    } catch (Exception e) {
 return output;
    }
}
return output;

我的问题是,当我调试这个时,handleText 被包含标签的文本调用!就好像它只深入一层。有人知道为什么吗?我需要对 HTMLParser 做一些简单的事情(没有太多使用它)来启用嵌套标签的“正确”行为吗?

PS - 我自己想出来了 - 请参阅下面的答案。简短的回答是,如果您传递 HTML,而不是预先转义的 HTML,它就可以正常工作。哎哟!希望这对其他人有帮助。

<span>example with <a href="#">nested</a> <p>more nesting</p>
</span> <!-- all this gets thrown together -->

最佳答案

对于我来说,在 XP 上使用 JDK6 似乎工作得很好。我用 head 和 body 标签包装了您的示例 HTML。我得到三行输出:

a) 示例 b) 嵌套 c) 更多嵌套

这是我使用的代码:

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

public class ParserCallbackText extends HTMLEditorKit.ParserCallback
{
    public void handleText(char[] data, int pos)
    {
        System.out.println( data );
    }

    public static void main(String[] args)
        throws Exception
    {
        Reader reader = getReader(args[0]);
        ParserCallbackText parser = new ParserCallbackText();
        new ParserDelegator().parse(reader, parser, true);
    }

    static Reader getReader(String uri)
        throws IOException
    {
        // Retrieve from Internet.
        if (uri.startsWith("http:"))
        {
            URLConnection conn = new URL(uri).openConnection();
            return new InputStreamReader(conn.getInputStream());
        }
        // Retrieve from file.
        else
        {
            return new FileReader(uri);
        }
    }
}

关于java - 为什么 Swing Parser 的 handleText 不处理嵌套标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1589241/

相关文章:

java - 如何阻止 netty bootstrap 监听和接受新连接

javascript - 网格中的多个视频的视频缩略图是重复的

css - DOM 中 'undefined' CSS 属性的性能成本是多少?

java - JSoup 在网页上看不到表格

python - 尝试解析表中的表

java - 在 java 构造期间将 `this` 作为参数传递

java - Map-Reduce 中的改组

java - 如何在不关闭前一个 shell 的情况下打开弹出 shell

javascript - 如何在选定元素之后获取所有元素

html - 仅使用不使用 javascript 的 css 在悬停时显示叠加层