使用dom4j解析XML时候忽略DTD文件

官方包下载地址: http://www.dom4j.org/download.html
转载: http://www.blogjava.net/rain1102/archive/2009/09/07/290063.html
当你用domj读取一个有dtd验证的xml文件,同时你的网络是不通的情况下。会出现以下错误:
Caused by:
org.dom4j.DocumentException: www.bea.com Nested exception: www....com
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.dom4j.io.SAXReader.read(SAXReader.java:264)


参照: javaeye上另一文章方法:声明本地的dtd验证
hibernate.sourceforge.net Nested exception: hibern
http://cherryqq.iteye.com/blog/401862
处理方法:
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "file:///F:/hibernate-test/classes/hibernate-mapping-2.0.dtd">

就可以了。
但这样很麻烦.


其实我们的XML肯定是合法的,不需要验证。
而设置不需要验证,只需要设置DocumentBuilderFactory.setValidating(false)
就可以达到效果了,但是解析器还是会读取DTD的,解决的方法是实现EntityResolver接口,具体代码如下:

import Java.io.ByteArrayInputStream;
import Java.io.IOException;

import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class IgnoreDTDEntityResolver implements EntityResolver {

 @Override
 public InputSource resolveEntity(String publicId, String systemId)
   throws SAXException, IOException {
        return new InputSource(
             new ByteArrayInputStream(
                   "<?xml version='1.0' encoding='UTF-8'?>".getBytes()
    ));
 }

}

然后设置SAXReader 对象如下:
SAXReader reader = new SAXReader();
reader.setEntityResolver(new IgnoreDTDEntityResolver()); 

就行了

另外一种方式为:
SAXReader xppReader = new SAXReader();
xppReader.setValidation(false);// 不验证xml文件内的dtd
xppReader.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId,
String systemId) throws SAXException, IOException {
InputStream stream = XmlUtil.class.getClassLoader().getResourceAsStream("***.dtd");
InputSource is = new InputSource(stream);
is.setPublicId(publicId);
is.setSystemId(systemId);
return is;
}
});

你可能感兴趣的:(java,html,xml,.net,Hibernate)