當我們使用 XmlWriter 配合 StringBuilder 建立xml文件時,會產生結果是 UTF-16 的 xml 文件
即使 XmlWriter 有配合 XmlWriterSetting 設定為 UTF-8 但結果還是 UTF-16
我網路上找了一下解決方式 整理出以下是比較好的解決方式 請參考程式碼
最終還是要靠 StreamReader 轉一次
Encoding enc = Encoding.UTF8;
XmlWriterSettings xws = new XmlWriterSettings();
xws.Encoding = enc;
xws.Indent = true;
MemoryStream ms = new MemoryStream();
string strXml = "";
using (XmlWriter writer = XmlWriter.Create(ms, xws))
{
writer.WriteStartDocument();
writer.WriteStartElement("rss");
writer.WriteAttributeString("version", "2.0");
writer.WriteStartElement("channel");
// channel data
writer.WriteElementString("title", "最新文章");
...(XML 資料)......
writer.WriteEndElement(); // channel end
writer.WriteEndElement(); //rss end
writer.WriteEndDocument();
writer.Flush();
StreamReader reader = new StreamReader(ms, enc, true);
ms.Seek(0, SeekOrigin.Begin);
strXml = reader.ReadToEnd();
}