您的位置:首页 > 其它

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

2018-11-20 10:25 197 查看

转自:https://www.geek-share.com/detail/2604945926.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("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
 }

}

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

一切ok。

注:有问题,记得问度娘

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: