六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 13|回复: 0

dom4j解析XML忽略DTD请求

[复制链接]

升级  20%

2

主题

2

主题

2

主题

童生

Rank: 1

积分
10
 楼主| 发表于 2013-2-3 10:43:16 | 显示全部楼层 |阅读模式
最近在做一个解析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!");
        }
    }
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表