2008-10-28 47 views
13

我得到了dtd文件,我不能刪除它。當我嘗試在Java中解析它時,我得到了「由java.net.SocketException:網絡無法訪問:連接引起的」,因爲它的遠程dtd。我可以禁用某種方式dtd檢查?如何在運行時在java的xpath中禁用dtd?

回答

18

你應該能夠指定你自己的EntityResolver,或者使用你的解析器的特定功能?有些方法請參見here

一個更完整的例子:

<?xml version="1.0"?> 
<!DOCTYPE foo PUBLIC "//FOO//" "foo.dtd"> 
<foo> 
    <bar>Value</bar> 
</foo> 

和XPath用法:

import java.io.File; 
import java.io.IOException; 
import java.io.StringReader; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.xpath.XPath; 
import javax.xml.xpath.XPathFactory; 

import org.w3c.dom.Document; 
import org.xml.sax.EntityResolver; 
import org.xml.sax.InputSource; 
import org.xml.sax.SAXException; 

public class Main { 

    public static void main(String[] args) throws Exception { 
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder = factory.newDocumentBuilder(); 

     builder.setEntityResolver(new EntityResolver() { 

      @Override 
      public InputSource resolveEntity(String publicId, String systemId) 
        throws SAXException, IOException { 
       System.out.println("Ignoring " + publicId + ", " + systemId); 
       return new InputSource(new StringReader("")); 
      } 
     }); 
     Document document = builder.parse(new File("src/foo.xml")); 
     XPathFactory xpathFactory = XPathFactory.newInstance(); 
     XPath xpath = xpathFactory.newXPath(); 
     String content = xpath.evaluate("/foo/bar/text()", document 
       .getDocumentElement()); 
     System.out.println(content); 
    } 
} 

希望這有助於...

+0

謝謝,這減少了一些單元測試我被7 – 2008-11-13 17:38:41

2

我以前有這個問題。我通過下載和存儲DTD的本地副本,然後根據本地副本進行驗證來解決此問題。您需要編輯XML文件以指向本地副本。

<!DOCTYPE root-element SYSTEM "filename"> 

多一點的信息在這裏:http://www.w3schools.com/dtd/dtd_intro.asp

我想你也可以手動設置某種validateOnParse屬性設置爲「假」在你的解析器。取決於你用來解析XML的庫。

此處瞭解詳情:http://www.w3schools.com/dtd/dtd_validation.asp

13

這爲我工作:

SAXParserFactory saxfac = SAXParserFactory.newInstance(); 
    saxfac.setValidating(false); 
    try { 
    saxfac.setFeature("http://xml.org/sax/features/validation", false); 
    saxfac.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); 
    saxfac.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); 
    saxfac.setFeature("http://xml.org/sax/features/external-general-entities", false); 
    saxfac.setFeature("http://xml.org/sax/features/external-parameter-entities", false); 
    } 
    catch (Exception e1) { 
    e1.printStackTrace(); 
    } 
+3

+1的因素做 - 這是這裏最好的答案 - 但是僅僅使用這一行就足夠了:``saxfac.setFeature(「http://apache.org/xml/features/nonvalidating/load-external-dtd」,false);``` – 2010-10-23 09:17:51