2010-10-11 29 views
1

任何人都可以告訴我如何將字符串轉換爲android中的xml文件?將字符串轉換爲android中的xml文件

謝謝

+0

該字符串是否已經是XML格式並且您想要創建一個內存中的對象?或者你想輸出一個字符串作爲完整XML文檔的一部分嗎? – 2010-10-11 13:41:22

+0

是的字符串已經在xml中。我想成爲一個xml文檔 – mohan 2010-10-11 14:31:30

回答

0

如果應用程序很簡單並且不需要太多的xml操作性能,那麼DOM應該做到這一點。否則,請嘗試使用SAX,這可以在某些場合提高性能。看看this教程,它很好地解釋了它們之間的差異。

2

最安全的方法是這樣的:

Document doc = DocumentBuilderFactory 
    .newInstance() 
    .newDocumentBuilder() 
    .parse(
      new InputSource(
        new StringReader(string) 
      ) 
    ); 

有人說,你應該關閉StringReader,but that doesn't have any practical benefit in this case

有使用ByteArrayInputStream的另一種解決方案:

Document doc = DocumentBuilderFactory 
    .newInstance() 
    .newDocumentBuilder() 
    .parse(
      new ByteArrayInputStream(
        string.getBytes("UTF-8") 
      ) 
    ); 

確保您使用string.getBytes,otherwise it uses the system default encoding,這可能取決於你所運行的平臺改變時明確指定編碼。似乎UTF-8是解析方法想要的,but it's not in the docs