【问题标题】:How to write custom ContentHandler using Apache Tika?如何使用 Apache Tika 编写自定义 ContentHandler?
【发布时间】:2013-10-10 13:32:57
【问题描述】:

我想使用 Apache Tika 从 HTML 文件中提取一些标签内的文本,如 <dt><dd> 等。

所以我正在编写自定义ContentHandler,它应该从这些标签中提取信息。

我的自定义ContentHandler 代码如下所示。它尚未完成,但已无法按预期工作:

public class TableContentHandler implements ContentHandler {

    // key = abbreviation
    // value = information / description for abbreviation
    private Map<String, String> abbreviations = new HashMap<String, String>();

    // current abbreviation
    private String abbreviation = null;

    // <dd> element contains abbreviation. So this boolean variable will be set when
    // <dd> element is found
    private boolean ddElementStarted = false;

    // this method is not giving contents within <dd> and </dd> tags
    public void characters(char[] chars, int arg1, int arg2) throws SAXException {
            if(ddElementStarted) {
                    System.out.println("chars found...");
            }
    }

    // set boolean ddElementStarted to true to indicate that content handler found 
    // <dd> element
    public void startElement(String arg0, String element, String arg2, Attributes arg3) throws SAXException {
            if(element.equalsIgnoreCase("dd")) {
                    ddElementStarted = true;
            }
    }
}

这里我的假设是,只要内容处理程序进入 startElement() 方法并且元素名称为 dd 然后我将设置 ddElementStarted = true 然后在 &lt;dd&gt;&lt;/dd&gt; 元素中获取内容,我将签入characters() 方法。

characters() 方法中,我正在检查ddElementStarted = truechars 数组是否将包含在&lt;dd&gt;&lt;/dd&gt; 元素中,但它不起作用:(

我想知道

  1. 我的方向正确吗?
  2. 这是使用 Tika 解析 HTML 的正确方法吗?或者有没有其他办法?
  3. 我应该选择另一个 HTML 解析 API,比如 JSoup 吗?我只需要来自几个标签的信息,例如,我对 HTML 页面的其余部分不感兴趣。
  4. 有没有办法在Apache Tika 中指定XPath 表达式?我无法在Tika in Action book 中找到此信息。

【问题讨论】:

    标签: java html-parsing apache-tika


    【解决方案1】:

    简单的解决方案是Jsoup。我们可以轻松地获取任何标签内的值。所以不用编写新的 ContentHandler 只需使用 JSoup 来解析。

    【讨论】:

      猜你喜欢
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多