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

原文:http://www.blogjava.net/rain1102/archive/2009/08/06/290063.html



要这么做是因为Server返回给我们的XML肯定是合法的,不需要验证。

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

package com.founder.demo;

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("".getBytes()));
 }

}

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

一切ok。


你可能感兴趣的:(xml)