Xml序列化UTF-8格式錯誤

我須要獲得一個類的Xml序列化後的字符串html

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會提示以下錯誤ide

沒法顯示 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()一下獲得的字符串就能夠,試了確實如此。spa

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

默認的StringWriter獲得的序列化的string是orm

<?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屬性xml

public class StringUTF8Writer : System.IO.StringWriter
{
    public override Encoding Encoding 
    { 
        get { return Encoding.UTF8; }
    }
}
相關文章
相關標籤/搜索