当我在这个方法中解析我的xml文件(变量f)时,我收到一个错误
C:\ Documents and Settings\joe\Desktop\aicpcudev\OnlineModule\map.dtd(系统找不到指定的路径)
我知道我没有dtd,也不需要它.如何在忽略DTD引用错误的同时将此File对象解析为Document对象?
private static Document getDoc(File f, String docId) throws Exception{ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(f); return doc; }
jt... 128
尝试在DocumentBuilderFactory上设置功能:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setNamespaceAware(true); dbf.setFeature("http://xml.org/sax/features/namespaces", false); dbf.setFeature("http://xml.org/sax/features/validation", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder db = dbf.newDocumentBuilder(); ...
最后,我认为这些选项特定于解析器实现.以下是Xerces2的一些文档,如果有帮助的话.
尝试在DocumentBuilderFactory上设置功能:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setNamespaceAware(true); dbf.setFeature("http://xml.org/sax/features/namespaces", false); dbf.setFeature("http://xml.org/sax/features/validation", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder db = dbf.newDocumentBuilder(); ...
最后,我认为这些选项特定于解析器实现.以下是Xerces2的一些文档,如果有帮助的话.
与@anjanb建议的方法类似
builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId.contains("foo.dtd")) { return new InputSource(new StringReader("")); } else { return null; } } });
我发现只返回一个空的InputSource也能正常工作?
我发现一个问题,其中DTD文件与XML一起位于jar文件中。我根据此处的示例解决了该问题,如下所示:-
DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId.contains("doc.dtd")) { InputStream dtdStream = MyClass.class .getResourceAsStream("/my/package/doc.dtd"); return new InputSource(dtdStream); } else { return null; } } });