Java SAX 解析器引发 UnknownHostException
我想要解析的 XML 文件以以下开头:
<!DOCTYPE plist PUBLIC "-//...//DTD PLIST 1.0//EN" "http://www.....dtd">
因此,当我启动 SAX praser 时,它会尝试在线访问此 DTD,并且我收到 java.net.UnknownHostException。
- 在将 XML 文件提供给 SAX 解析器之前,我无法对其进行修改
- 即使没有 Internet 连接,我也必须运行
如何更改 SAX 解析器的行为,使其不会尝试加载 DTD? 谢谢。
javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
factory.setValidating(false);
javax.xml.parsers.SAXParser parser = factory.newSAXParser();
parser.parse(xmlFile, handler);
The XML file I want to parse starts with :
<!DOCTYPE plist PUBLIC "-//...//DTD PLIST 1.0//EN" "http://www.....dtd">
So when I start the SAX praser, it tries to access this DTD online, and I get a java.net.UnknownHostException.
- I cannot modify the XML file before feeding it to the SAX parser
- I have to run even with no internet connection
How can I change the SAX Parser behaviour so that it does not try to load the DTD ?
Thanks.
javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
factory.setValidating(false);
javax.xml.parsers.SAXParser parser = factory.newSAXParser();
parser.parse(xmlFile, handler);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,结果是
parse()
方法使用传入解析方法的处理程序覆盖了之前设置的任何实体解析器。 以下代码应该可以工作:Ok, turns out the
parse()
method overrides any previously set entity resolvers with the handler passed in to the parse method. The following code should work:使用 XMLReader 而不是 SAXParser。
它也应该与 SAXParser 一起使用,但由于某些原因它不能。
Use XMLReader instead of SAXParser.
It should also work with SAXParser, but for some reasons it doesn't.
您可以实现自定义
EntityResolver
,它用于在 XML 解析期间查找外部实体。在您的自定义 EntityResolver 中,始终返回 null。 我认为这应该可以解决这个问题。
You can implement a custom
EntityResolver
which is what is used to lookup external entities during XML parsing.And in your custom EntityResolver, just always return null. I think that should fix this problem.
您应该提供 EntityResolve 来解决问题。 我建议您编写一个解析器,它知道如何在本地读取 DTD(前提是您将它们与应用程序一起提供)。 否则,像 Gowri 建议的那样返回 null。
您可能需要阅读 API 文档。
yc
You should provide an EntityResolve to have the problem resolve. I will recommend you to write a resolver that will know how to read the DTDs locally instead (provided that you have them shipped together with your application). Otherwise, return null like Gowri suggested.
You might want to read up the the API doc.
yc