dom4j解析XML忽略DTD请求

最近在做一个解析XML的功能,功能测试无问题。一次偶然的情况发现在断网情况,老是报解柝失败。研究最后原来是dom解析器在解析XML头DTD,会向DTD上的服务地址请求,在联网环境正常,在断网环境无响应,导致解析失败。研究了相关的API,在百度搜索了一把,找到以下解决方案:
需要设置DocumentBuilderFactory.setValidating(false)就可以达到效果了,但是解析器还是会读取DTD的,解决的方法是实现EntityResolver接口,具体代码如下:

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


/**
* 获取Document对象
* @param xmlPath
* @return
*/
public static Document getDocument(String xmlPath)
{
SAXReader reader = new SAXReader();
reader.setValidation(false);
try
{
reader.setEntityResolver(new IgnoreDTDEntityResolver());
return reader.read(new File(xmlPath));
}
catch(DocumentException e)
{
throw new java.lang.IllegalArgumentException("Can't parse the XML!");
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值