使DocumentBuilder.parse忽略DTD引用 [英] Make DocumentBuilder.parse ignore DTD references

查看:267
本文介绍了使DocumentBuilder.parse忽略DTD引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在此方法中解析我的xml文件(变量f)时,我收到错误


C:\Documents and Settings \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\知道我没有dtd,也不需要它。如何在忽略DTD引用错误的同时将此File对象解析为Document对象?

  private static Document getDoc(File f,String docId)抛出异常{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
文件doc = db.parse(f);


返回doc;
}


解决方案

类似于建议由 @anjanb

  builder.setEntityResolver(new EntityResolver(){
@Override
public InputSource resolveEntity(String publicId,String systemId)
抛出SAXException,IOException {
if(systemId.contains(foo.dtd)){
返回新的InputSource(new StringReader());
} else {
返回null;
}
}
});

我发现只返回一个空的InputSource也能正常工作?


When I parse my xml file (variable f) in this method, I get an error

C:\Documents and Settings\joe\Desktop\aicpcudev\OnlineModule\map.dtd (The system cannot find the path specified)

I know I do not have the dtd, nor do I need it. How can I parse this File object into a Document object while ignoring DTD reference errors?

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;
}

解决方案

A similar approach to the one suggested by @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;
            }
        }
    });

I found that simply returning an empty InputSource worked just as well?

这篇关于使DocumentBuilder.parse忽略DTD引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆