【发布时间】: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 然后在 <dd> 和 </dd> 元素中获取内容,我将签入characters() 方法。
在characters() 方法中,我正在检查ddElementStarted = true 和chars 数组是否将包含在<dd> 和</dd> 元素中,但它不起作用:(
我想知道
- 我的方向正确吗?
- 这是使用 Tika 解析 HTML 的正确方法吗?或者有没有其他办法?
- 我应该选择另一个 HTML 解析 API,比如 JSoup 吗?我只需要来自几个标签的信息,例如,我对 HTML 页面的其余部分不感兴趣。
- 有没有办法在Apache Tika 中指定
XPath表达式?我无法在Tika in Actionbook 中找到此信息。
【问题讨论】:
标签: java html-parsing apache-tika