最近在做一个解析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!");
}
}
需要设置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!");
}
}
本文讨论了在解析XML文件时遇到的DTD服务请求问题,特别是在断网环境下解析失败的原因。通过设置DocumentBuilderFactory的验证选项为false,并实现EntityResolver接口来忽略DTD的验证,从而解决了XML解析失败的问题。
414

被折叠的 条评论
为什么被折叠?



