2012-01-12 19 views
4

我想與SAXReader 離線一起工作,問題是SAXReader正在驗證DTD的xml聲明。我不想更改DTD或XML中的其他任何內容。從本網站和其他來源上搜索,我發現2個答案是沒有幫助我:如何使用dom4j SAXReader離線?

  1. 使用的EntityResolver繞過網絡呼叫
  2. 使用setIncludeExternalDTDDeclarations(假)的

例什麼我試圖做的:

protected Document getPlistDocument() throws MalformedURLException, 
DocumentException { 
    SAXReader saxReader = new SAXReader(); 
    saxReader.setIgnoreComments(false); 
    saxReader.setIncludeExternalDTDDeclarations(false); 
    saxReader.setIncludeInternalDTDDeclarations(true); 
    saxReader.setEntityResolver(new MyResolver()); 
    Document plistDocument = saxReader.read(getDestinationFile().toURI().toURL()); 
    return plistDocument; 
} 

public class MyResolver implements EntityResolver { 
    public InputSource resolveEntity (String publicId, String systemId) 
    { 
     if (systemId.equals("http://www.myhost.com/today")) { 
      // if we want a custom implementation, return a special input source 
      return null; 

     } else { 
      // use the default behaviour 
      return null; 
     } 
    } 
} 

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 

我仍然無法脫機工作,請指教...謝謝

堆棧跟蹤:

14:20:44,358 ERROR [ApplicationBuilder] iphone build failed: Resource Manager - Problem handle Root.plist: www.apple.com Nested exception: www.apple.com 
com.something.builder.sourcemanager.exception.SourceHandlingException: Resource Manager - Problem handle Root.plist: www.apple.com Nested exception: www.apple.com 
**** 
**** 
Caused by: org.dom4j.DocumentException: www.apple.com Nested exception: www.apple.com 
at org.dom4j.io.SAXReader.read(SAXReader.java:484) 
at org.dom4j.io.SAXReader.read(SAXReader.java:291) 
... 10 more 
+0

你在找什麼錯誤?它會拋出任何異常嗎?你能發佈這種異常的消息和堆棧跟蹤嗎? – 2012-01-12 08:36:17

回答

5

你的實體解析器不處理任何事情(因爲它總是返回null)。當系統ID是http://www.apple.com/DTDs/PropertyList-1.0.dtd時,讓它將InputSource返回到實際的DTD文件,因爲那是dom4j嘗試下載的DTD。

public class MyResolver implements EntityResolver { 
    public InputSource resolveEntity (String publicId, String systemId) 
    { 
     if (systemId.equals("http://www.apple.com/DTDs/PropertyList-1.0.dtd")) { 
      return new InputSource(MyResolver.class.getResourceAsStream("/dtds/PropertyList-1.0.dtd"); 
     } else { 
      // use the default behaviour 
      return null; 
     } 
    } 
} 

此實現中,例如,返回從類路徑DTD(在包dtds)。您只需自己下載DTD,並將其捆綁到您的應用程序中,包裝爲dtds

0

請注意,您實際上並未針對DTD進行驗證。要做到這一點,你需要:

SAXReader saxReader = new SAXReader(true); 

否則JB的權利 - 他在我面前3分鐘得到了!

0

作爲一個選項,如果您只想離線使用SAXReader,請通過http://apache.org/xml/features/nonvalidating/load-external-dtd Xerces 功能禁用其外部DTD提取。

根據Xerces features documentation,將其設置爲false使得SAXReader完全忽略外部DTD。

This SO answer有一個代碼示例。