天天看點

System.Xml.XmlException: 根級别上的資料無效

使用Asp.net C#時.出現以下問題

在以下代碼中,運作進會抛出 [ System.Xml.XmlException: 根級别上的資料無效。] 的異常,問題

MemoryStream stream = new MemoryStream();

XmlWriter w = XmlTextWriter.Create(stream);

w.WriteStartDocument();

w.WriteElementString("abc","test");

w.WriteEndDocument();

w.Flush();

w.Close();

string xml = Encoding.UTF8.GetString(stream.ToArray());

XmlDocument xDoc = new XmlDocument();

xDoc.LoadXml(xml);

經過仔細調試發現問題出現在. UTF8或者Unicode編碼轉換時,第一個字元轉換會出現一個?号。

是以,為避免異常。還應加上。

xml = xml.Substring(1, xml.Length - 1);

然後再 LoadXml(xml) 就不會出錯了。

轉載于:https://www.cnblogs.com/ganmk/archive/2011/06/04/2072459.html