229313998qq.com 发表于 2013-2-3 10:43:16

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!");
      }
    }
页: [1]
查看完整版本: dom4j解析XML忽略DTD请求