Xml序列化UTF-8格式錯誤


我需要得到一個類的Xml序列化后的字符串

using (System.IO.MemoryStream mem = new System.IO.MemoryStream())
{

    XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8);
    XmlSerializer xz = new XmlSerializer(t.GetType());
    xz.Serialize(writer, t);
    writer.Close();
    byte[] bytes = mem.ToArray();
    return System.Text.Encoding.UTF8.GetString(bytes);
}

得到的字符串卻被提示格式錯誤,放到IE會提示如下錯誤

無法顯示 XML 頁。 
使用 樣式表無法查看 XML 輸入。請更正錯誤然后單擊 刷新按鈕,或以后重試。 


--------------------------------------------------------------------------------

文檔的頂層無效。處理資源 'file:///C:/Documents and Settings/Administrator/桌面/test.txt.xml' 時出錯。第 1 行,位置: 1 

<?xml version="1.0" encoding="utf-8"?><LocalUIForm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd...

 百思不解!查網上,說Trim()一下得到的字符串就可以,試了確實如此。

這提供了另一種方式,利用子類StringWriter
http://stackoverflow.com/questions/1564718/using-stringwriter-for-xml-serialization

默認的StringWriter得到的序列化的string是

<?xml version="1.0" encoding="utf-16" ?> 
using (StringUTF8Writer sw = new StringUTF8Writer())
{
    XmlSerializer xz = new XmlSerializer(t.GetType());
    xz.Serialize(sw, t);
    return sw.ToString();
}

 我希望得到的xml是utf-8,於是簡單重寫EnCoding屬性

public class StringUTF8Writer : System.IO.StringWriter
{
    public override Encoding Encoding 
    { 
        get { return Encoding.UTF8; }
    }
}

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM