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

转自:https://blog.csdn.net/lan861698789/article/details/20492661

要这么做是因为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("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
 }

}

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

一切ok。

注:有问题,记得问度娘

猜你喜欢

转载自blog.csdn.net/qq_36322492/article/details/84286268