【问题标题】:NekoHTML SAX fragment parsingNekoHTML SAX 片段解析
【发布时间】: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


【解决方案1】:

我终于明白了!

实际上,我在 GWT 应用程序中解析我的 HTML 字符串,我在其中添加了 gwt-dev.jar 依赖项。这个 jar 包了很多外部库,比如 xercesImpl。但是嵌入式 xerces 类的版本与 NeokHTML 要求的不匹配。

作为一个(奇怪的)结果,NeokHTML SAX 解析器在使用 gwt-dev 嵌入式 xerces 版本时似乎没有使用任何自定义功能。

因此,我不得不重新编写一些代码以删除 gwt-dev 依赖项,顺便说一下,不建议将其添加到任何标准 GWT 项目中。

【讨论】:

  • 更具体地说,gwt-dev.jar 在 1.9.13 版本中包含 NekoHTML,该版本存在片段解析问题。片段解析适用于 1.9.11 和 1.9.14,没有运气 :-(
猜你喜欢
  • 2011-02-19
  • 1970-01-01
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
  • 2013-01-22
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多