Unity3d XmlException: Text node cannot appear in this state的方案

來源:互聯網
上載者:User

標籤:except   問題   encoding   utf8   編碼   檔案   unity   方案   write   

這個問題是utf-8編碼的問題,如果是utf-8+bom那麼就會出現這種問題,如果是單純的utf-8就沒有這種問題(當然如果你把他完全變成ansi,那也行) 
我在讀寫xml的時候遇到這個問題。查了好久在老外的一個網上看到瞭解決的方法。還有我自己總結的一些方法。 


    public bool LoadXml(string xmlFile) 
    { 
        if (xmlDocument == null) 
        { 
            throw new ArgumentNullException("xmlDocument"); 
        } 


        if (xmlFile == null || xmlFile.Length == 0) 
        { 
            throw new ArgumentNullException("xmlFile"); 
        } 


// Debug.Log(xmlFile); 
// TextReader tr = new StringReader(xmlFile); 
//        xmlDocument.Load(tr); 
  
 System.IO.StringReader stringReader = new System.IO.StringReader(xmlFile); 
 stringReader.Read(); // 跳過 BOM 
 System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); 
 xmlDocument.LoadXml(stringReader.ReadToEnd()); 
        return true; 
  
    } 
這個是bom的解釋網上很多,我不解釋了http://www.cnblogs.com/zhongru_tu/archive/2008/04/11/1147792.html 
這是一個自己寫的匯入xml的方法,注釋的部分是我一開始使用的方法,沒有注釋的部分是我修改過的。這樣你在讀取xml的時候就可以跳過bom了. 


如果你不需要發布為網頁形式,那麼還有一種方法也可以起到這樣的效果,那就是重新寫一下xml,徹底改變它的編碼方式讓其不帶bom 
代碼如下: 

 Encoding utf8NoBom = new UTF8Encoding(false); 
 string fileString = File.ReadAllText(writeUrl,utf8NoBom); 
 File.WriteAllText(writeUrl,fileString,utf8NoBom); 
注意你需要使用幾個命名空間 

using System.Xml; 
using System.Text; 

using System; 
using System.IO; 
當然有時候你會發現unity雖然你寫了命名空間但是有些類你還是找不到,那麼你要到網上下專門的動態庫(dll)放到Plugins檔案夾下,當然有些讀寫本地檔案的類在發布為網頁形式的時候你是不能夠使用的。 

最後還有一點,你使用了上面的方法以後一定記住把你的xml檔案的編碼改為utf-8+bom這種格式,因為我們這個是對bom格式的讀取。 


還有一些其他的小方法你用其他編輯軟體改為utf-8不帶bom的有時候也能解決,但當你改完後,還不能解決的時候,上面的方法對你也許有協助

Unity3d XmlException: Text node cannot appear in this state的方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.