zoukankan      html  css  js  c++  java
  • Unity3d XmlException: Text node cannot appear in this state的方案

    这个问题是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的有时候也能解决,但当你改完后,还不能解决的时候,上面的方法对你也许有帮助

  • 相关阅读:
    word2013下,公式居中,编号右对齐
    Linux系统下,anaconda3与系统python共存
    LeetCode: 496 Next Greater Element I(easy)
    LeetCode: 463 Island Perimeter(easy)
    LeetCode: 620 Not Boring Movies(easy)
    C++: 其他类型转string
    LeetCode: 412 Fizz Buzz(easy)
    LeetCode: 344 Reverse String
    LeetCode: 566 Reshape the Matrix
    LeetCode: 575 Distribute Candies(easy)
  • 原文地址:https://www.cnblogs.com/lancidie/p/9472704.html
Copyright © 2011-2022 走看看