jdom 或 dom4j读取xml文件时如何让dtd验证使用本地dtd文件或者不生效

一、写在所有之前:
因为dom4j和jdom在这个问题上处理的方法是一模一样的,只是一个是SAXBuilder 一个SAXReader,这里以jdom距离,至于dom4j只需要同理替换一下就可以了。
二、问题发生的情况
当你用jdom读取一个有dtd验证的xml文件,同时你的网络是不通的情况下。会出现以下错误:
1,代码如下

None.gif package  dom;
None.gif
None.gif
import  java.io.File;
None.gif
None.gif
import  org.jdom.Document;
None.gif
import  org.jdom.input.SAXBuilder;
None.gif
ExpandedBlockStart.gif
public   class  TestJdom  {
ExpandedSubBlockStart.gif    
public static void main(String[] args) {
InBlock.gif        File file 
= new File("./src/dom/aiwf_aiService.xml");
ExpandedSubBlockStart.gif        
if (file.exists()) {
InBlock.gif            SAXBuilder builder 
= new SAXBuilder();
ExpandedSubBlockStart.gif            
try {
InBlock.gif                Document doc 
= builder.build(file);
InBlock.gif                System.out.println(doc);
ExpandedSubBlockStart.gif            }
 catch (Exception e) {
InBlock.gif                e.printStackTrace();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockStart.gif        }
 else {
InBlock.gif            System.out.println(
"can not find xml file:"
InBlock.gif                    
+ file.getAbsolutePath());
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

2,xml文件

None.gif xml version="1.0" encoding="GBK" ?>
None.gif
DOCTYPE workflow PUBLIC "-//OpenSymphony Group//DTD OSWorkflow 2.8//EN" "http://www.opensymphony.com/osworkflow/workflow_2_8.dtd" >
None.gif
< workflow >
                ...............
None.gif
workflow >


3,错误如下

None.gif java.net.SocketException: Permission denied: connect
None.gif    at java.net.PlainSocketImpl.socketConnect(Native Method)
None.gif    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:
333 )
None.gif    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:
195 )
None.gif    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:
182 )
None.gif    at java.net.Socket.connect(Socket.java:
507 )
None.gif    at java.net.Socket.connect(Socket.java:
457 )
None.gif    at sun.net.NetworkClient.doConnect(NetworkClient.java:
157 )
None.gif    at sun.net.www.http.HttpClient.openServer(HttpClient.java:
365 )
None.gif    at sun.net.www.http.HttpClient.openServer(HttpClient.java:
477 )
None.gif    at sun.net.www.http.HttpClient.
< init > (HttpClient.java: 214 )
None.gif    at sun.net.www.http.HttpClient.New(HttpClient.java:
287 )
None.gif    at sun.net.www.http.HttpClient.New(HttpClient.java:
299 )
None.gif    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:
792 )
None.gif    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:
744 )
None.gif    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:
669 )
None.gif    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:
913 )
None.gif    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:
973 )
None.gif    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(XMLEntityManager.java:
905 )
None.gif    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(XMLEntityManager.java:
872 )
None.gif    at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(XMLDTDScannerImpl.java:
282 )
None.gif    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDispatcher.dispatch(XMLDocumentScannerImpl.java:
1021 )
None.gif    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:
368 )
None.gif    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:
834 )
None.gif    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:
764 )
None.gif    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:
148 )
None.gif    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:
1242 )
None.gif    at org.jdom.input.SAXBuilder.build(SAXBuilder.java:
453 )
None.gif    at org.jdom.input.SAXBuilder.build(SAXBuilder.java:
810 )
None.gif    at org.jdom.input.SAXBuilder.build(SAXBuilder.java:
789 )
None.gif    at dom.TestJdom.main(TestJdom.java:
26 )
None.gif

三、分析原因
当执行build的时候jdom分析到
DOCTYPE workflow PUBLIC "-/OpenSymphony Group//DTD OSWorkflow 2.8//EN" "http://www.opensymphony.com/osworkflow/workflow_2_8.dtd
就会去读取http://www.opensymphony.com/osworkflow/workflow_2_8.dtd 这里的dtd文件来验证,但是因为网络是不通的所以就会报socket错误。

四、解决办法
1,最开始查看jdom api发现了这样一个方法
builder.setValidation(false);
这样可以让jdom不做验证,但是结果依然出问题,查了一下原因,说虽然不验证但是还是会下载
2,参照jdom网站的FAQ  http://www.jdom.org/docs/faq.html#a0100
这是原文内容
None.gif How do I keep the DTD from loading? Even when I turn off validation the parser tries to load the DTD file.
None.gif
None.gifEven when validation is turned off, an XML parser will by default load the external DTD file in order to parse the DTD for external entity declarations. Xerces has a feature to turn off this behavior named "http://apache.org/xml/features/nonvalidating/load-external-dtd" and if you know you're using Xerces you can set this feature on the builder.
None.gif
None.gifbuilder.setFeature(
None.gif  "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
None.gif
None.gifIf you're using another parser like Crimson, your best bet is to set up an EntityResolver that resolves the DTD without actually reading the separate file.
None.gif
None.gifimport org.xml.sax.*;
None.gifimport java.io.*;
None.gif
None.gifpublic class NoOpEntityResolver implements EntityResolver {
None.gif  public InputSource resolveEntity(String publicId, String systemId) {
None.gif    return new InputSource(new StringBufferInputStream(""));
None.gif  }
None.gif}
None.gif
None.gifThen in the builderdot.gif
None.gif
None.gif
None.gifbuilder.setEntityResolver(new NoOpEntityResolver());
None.gif
None.gifThere is a downside to this approach. Any entities in the document will be resolved to the empty string, and will effectively disappear. If your document has entities, you need to setExpandEntities(false) code and ensure the EntityResolver only suppresses the DocType.
None.gif
里边教我们定义个类
ExpandedBlockStart.gif public   class  NoOpEntityResolver  implements  EntityResolver  {
ExpandedSubBlockStart.gif  
public InputSource resolveEntity(String publicId, String systemId) {
InBlock.gif            
return new InputSource(new StringBufferInputStream(""));
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif

通过builder.setEntityResolver(new NoOpEntityResolver())方法来隐蔽起dtd验证器。这样就不会出错了。试了一下确实没问题了。但要知道xml没有dtd验证是不好的,我们是否能让它使用本地dtd验证呢。例如本文的oswork
我把验证文件workflow_2_8.dtd拷贝到本地,能否验证的时候用本地的呢?
3,用本地dtd验证
方法有两种
方法一、更改xml中的doctype声明,但是一般情况下更改这个是不好的。更改后就不是标准的了。
方法二、验证期替换
看到上边FAQ讲的方法你是否有什么灵感呢?
看看下边这段代码

None.gif package  dom;
None.gif
None.gif
import  java.io.File;
None.gif
import  java.io.IOException;
None.gif
None.gif
import  org.jdom.Document;
None.gif
import  org.jdom.input.SAXBuilder;
None.gif
import  org.xml.sax.EntityResolver;
None.gif
import  org.xml.sax.InputSource;
None.gif
import  org.xml.sax.SAXException;
None.gif
ExpandedBlockStart.gif
public   class  TestJdom  {
ExpandedSubBlockStart.gif    
public static void main(String[] args) {
InBlock.gif        File file 
= new File("./src/dom/aiwf_aiService.xml");
ExpandedSubBlockStart.gif        
if (file.exists()) {
InBlock.gif            SAXBuilder builder 
= new SAXBuilder();
InBlock.gif            builder.setValidation(
false);
ExpandedSubBlockStart.gif            builder.setEntityResolver(
new EntityResolver() {
InBlock.gif                
public InputSource resolveEntity(String publicId,
ExpandedSubBlockStart.gif                        String systemId) 
throws SAXException, IOException {
InBlock.gif                    
return new InputSource("./workflow_2_8.dtd");
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }
);
ExpandedSubBlockStart.gif            
try {
InBlock.gif                Document doc 
= builder.build(file);
InBlock.gif                System.out.println(doc);
ExpandedSubBlockStart.gif            }
 catch (Exception e) {
InBlock.gif                e.printStackTrace();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockStart.gif        }
 else {
InBlock.gif            System.out.println(
"can not find xml file:"
InBlock.gif                    
+ file.getAbsolutePath());
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

对了,同样是自己实现一个EntityResolver(这里用了匿名类),不同的是在里边使用本地的dtd验证
另外,匿名类内部,似乎这样写起来更顺眼些

None.gif InputStream stream  =   new  FileInputStream(  " your dtd file path "  );
None.gif                    InputSource is 
=   new  InputSource(stream);
None.gif                    is.setPublicId(publicId);
None.gif                    is.setSystemId(systemId);
None.gif                    
return  is;

你可能感兴趣的:(xml,java)