4

我在使用 DOM 解析器解析带有 DOCTYPE 声明的 xhtml 时遇到问题。

错误:java.io.IOException:服务器返回 HTTP 响应代码:503 用于 URL: http ://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd%20

声明:DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd

有没有办法将 xhtml 解析为忽略 DOCTYPE 声明的 Document 对象。

4

4 回答 4

4

一个对我有用的解决方案是给 DocumentBuilder 一个返回空流的假解析器。这里有一个很好的解释(查看 kdgregory 的最后一条消息)

http://forums.sun.com/thread.jspa?threadID=5362097

这是kdgregory的解决方案:

documentBuilder.setEntityResolver(new EntityResolver()
        {
            public InputSource resolveEntity(String publicId, String systemId)
                throws SAXException, IOException
            {
                return new InputSource(new StringReader(""));
            }
        });
于 2010-07-30T14:28:57.437 回答
1

最简单的做法是在 DocumentBuilderFactory 中设置 validating=false。如果要进行验证,请下载 DTD 并使用本地副本。正如上面 Rachel 所评论的,这在WWW 联盟中进行了讨论。

简而言之,因为默认的 DocumentBuilderFactory 每次验证时都会下载 DTD,所以每次典型的程序员试图用 Java 解析 XHTML 文件时,W3 都会受到打击。他们负担不起这么多的流量,因此他们以错误响应。

于 2010-07-27T16:56:35.780 回答
1

解析器是下载 DTD 所必需的,但您可以通过在线设置独立属性来绕过它<?xml... ?>

但是请注意,此特定错误很可能是由 XML Schema 定义和 DTD URL 之间的混淆触发的。有关详细信息,请参见http://www.w3schools.com/xhtml/xhtml_dtd.asp。正确的是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
于 2010-04-14T20:35:07.390 回答
1

下面的代码片段不是假的解析器,而是指示解析器真正忽略 DOCTYPE 声明中的外部 DTD:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

(...)

DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setValidating(false);
f.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
DocumentBuilder builder = f.newDocumentBuilder();
Document document = builder.parse( ... )
于 2016-09-18T15:49:00.507 回答