---
title: "设置dom4j不检查xml中的dtd声明"
author: "chainhou"
date: "2012-12-21T18:50:08Z"
tags: []
categories: ["编程语言"]
slug: "dom4j-xml-dtd"
draft: false
lastmod: "2012-12-21T19:01:11Z"
id: 1752051
url: "https://chainhou.iteye.com/blog/1752051"
---

今天在做一个web应用部署验证功能。部署的时候需要通过解析其配置文件来得到具体的contextRoot,以此来判断是否和服务器上以存在的应用contextRoot冲突。解析的配置文件的时候，xml中有dtd声明，dom4j读取xml的时候应该是去联网获取dtd了，相应的dtd只在本地存在，所以按照dtd的url会返回404，造成读取xml失败

```java

Nested exception: java.io.FileNotFoundException: http://xxxxx/j2ee/dtds/xxxx.dtd
 at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1194)
 at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:973)
 at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(XMLEntityManager.java:905)

```

后来google了一下，这篇文章的方式可以解决
<http://blog.csdn.net/luo_yifan/article/details/5904369>
主要是设置一下SAXReader的EntityResolver,之后就不会再检查dtd了。 :idea: 

```java

		SAXReader saxReader = new SAXReader();
		saxReader.setEntityResolver(new EntityResolver() {  
			public InputSource resolveEntity(String publicId,  
			String systemId) throws SAXException, IOException {  
			InputSource is = new InputSource(new StringBufferInputStream(""));  
			is.setPublicId(publicId);  
			is.setSystemId(systemId);  
			return is;  
			}  
			}); 

```

需要注意的是：
```java
InputSource is = new InputSource(new StringBufferInputStream("")); 
```
这中间的StringBufferInputStream如果换成了自己传过来的inputstream，对于zip文件可能正常解析，对于FileInputStream,直接指向某个xml文件时，会出现IOException:Read error 原因还不清楚 :oops: