2013-09-16 46 views
1

我知道我爲什麼會收到這條消息,因爲服務器發出錯誤,沒有返回XML,而只是一條錯誤消息。有沒有辦法來檢查它是否是一個有效的XML,所以我沒有得到這個消息。原因:org.w3c.dom.DOMException:只允許一個根元素

我通過XML這種方法:

public Document getDomElement(String xml){ 
     Document doc = null; 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     try { 

      DocumentBuilder db = dbf.newDocumentBuilder(); 

      InputSource is = new InputSource(); 
       is.setCharacterStream(new StringReader(xml)); 
       doc = db.parse(is); 

      } catch (ParserConfigurationException e) { 
       Log.e("Error: ", e.getMessage()); 
       return null; 
      } catch (SAXException e) { 
       Log.e("Error: ", e.getMessage()); 
       return null; 
      } catch (IOException e) { 
       Log.e("Error: ", e.getMessage()); 
       return null; 
      } 
       // return DOM 
      return doc; 
    } 

感謝

回答

1

錯誤是非常簡單的,你的XML是什麼樣子(例如):

<root-element> 
    ... 
</root-element> 
<root-element> 
    ... 
</root-element> 
... 
<root-element> 
    ... 
</root-element> 

而XML只允許一個根元素,因此您需要爲所有「基本」元素創建一個「包裝器」元素,以便解析器工作。

+0

嗨,它給錯誤的原因是因爲通常一個XML被傳遞,它工作正常。但是現在它只是給出了幾行沒有任何XML格式的錯誤消息。我無法更改響應,所以我想檢查是否將有效的XML字符串傳遞給此方法或者是否有辦法捕獲此錯誤? – Diego

+0

當我說最後一句時,我想,當然我應該趕上DomException .. – Diego

+1

@Diego你是對的,我想你可以捕獲一個異常並在該場景中返回一個空文檔。 – alfasin

相關問題