【发布时间】:2011-09-03 17:00:57
【问题描述】:
我正在尝试使用 NekoHTML 解析一个简单的 HTML 片段:
<h1>This is a basic test</h1>
为此,我设置了一个 specific Neko feature 不让任何 HTML、HEAD 或 BODY 标记调用 startElement(..) 回调。
不幸的是,它对我不起作用。我当然错过了一些东西,但不知道会是什么。
这是一个非常简单的代码来重现我的问题:
public static class MyContentHandler implements ContentHandler {
public void characters(char[] ch, int start, int length) throws SAXException {
String text = String.valueOf(ch, start, length);
System.out.println(text);
}
public void startElement(String nameSpaceURI, String localName, String rawName, Attributes attributes) throws SAXException {
System.out.println(rawName);
}
public void endElement(String nameSpaceURI, String localName, String rawName) throws SAXException {
System.out.println("end " + localName);
}
}
和 main() 启动测试:
public static void main(String[] args) throws SAXException, IOException {
SAXParser saxReader = new SAXParser();
// set the feature like explained in documentation : http://nekohtml.sourceforge.net/faq.html#fragments
saxReader.setFeature("http://cyberneko.org/html/features/balance-tags/document-fragment", true);
saxReader.setContentHandler(new MyContentHandler());
saxReader.parse(new InputSource(new StringInputStream("<h1>This is a basic test</h1>")));
}
对应的输出:
HTML
HEAD
end HEAD
BODY
H1
This is a basic test
end H1
end BODY
end HTML
而我期待
H1
This is a basic test
end H1
有什么想法吗?
【问题讨论】:
-
如果将特征设置为 false,是否得到完全相同的输出?
标签: java html-parsing sax