【问题标题】:resolving entities for xhtml lacking doctype declaration with Java SAX使用 Java SAX 解析缺少 doctype 声明的 xhtml 实体
【发布时间】:2013-12-11 23:30:05
【问题描述】:

我正在尝试解析来自 Tika 服务器的 xhtml 输出。 xml 输入流(我通过 apache HttpClient 获得)声明了一个命名空间,但没有声明 dtd,根看起来像:

<html xmlns="http://www.w3.org/1999/xhtml">

如果我尝试使用 SAX 解析输入流,如果 xml 流包含实体,则会遇到错误

Exception in thread "main" org.xml.sax.SAXParseException; lineNumber: 47; columnNumber: 37; The entity "rsquo" was referenced, but not declared. 

我试图强制解析器使用 xhtml 1.1 dtd 的本地副本

    class XhtmlResolver implements EntityResolver {
        public InputSource resolveEntity(String publicId, String systemId) {
            InputStream in = getClass().getResourceAsStream("src/main/java/com/w3c/xhtml/xhtml11.dtd");
            return new InputSource(in);
        }
    }

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    XMLReader reader = saxParser.getXMLReader();
    reader.setEntityResolver(new XhtmlResolver());
    reader.parse(new InputSource(inputStream));

但它仍然没有解析实体。我仍然在其中包含实体的任何 xhtml 流上收到 SAXParseException。有人可以帮我从这里出去吗?

谢谢!

【问题讨论】:

    标签: java xml sax apache-tika


    【解决方案1】:

    您尚未发布实际给出错误的代码。但在 Tika 的情况下,这是因为 Tika 期望格式良好的 html 但没有得到。

    发生这种情况的一种常见情况是嵌套 ContentHandler 时,如下所示:

     ContentHandler handler = new BodyContentHandler(new ToXMLContentHandler());
    

    只需删除上面的包装并使用:

    ContentHandler handler = new ToXMLContentHandler();
    

    一切都会好起来的。

    如果这发生在其他代码 sn-p 中,请记住这是因为输入的 HTML 格式不正确。 详情请查看JIRA issue

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 2010-11-20
      • 1970-01-01
      • 2014-02-01
      • 2011-09-12
      • 2012-01-25
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多