Intro
使用 XmlWriter 需要設置 Encoding 時發生的問題Content
基本的用法是醬~var buffer = new StringBuilder(); using (var write = System.Xml.XmlWriter.Create(buffer)){ write.WriteStartElement("Transaction"); write.WriteAttributeString("Action", "AskData"); write.WriteEndElement(); }
如果要加一些參數的話, 就得設置 XmlWriterSettings
var buffer = new StringBuilder(); var setting = new System.Xml.XmlWriterSettings(); setting.Indent = true; setting.Encoding = new System.Text.UTF8Encoding(); using (var write = System.Xml.XmlWriter.Create(buffer, setting)){ write.WriteStartElement("Transaction"); write.WriteAttributeString("Action", "AskData"); write.WriteEndElement(); }
然後咱們就會發現, Indent 有作用, 但 Encoding 還是 utf-16
這是由於 dotNet 的字串本身就是utf-16編碼
所以咱們需要把 buffer 改成 Stream
var buffer = new System.IO.MemoryStream();
如果看到了如下圖的字串, 開頭有一段不明所以的空白
就是你得到了!! utf-8 的前置識別字元~請把它取消掉~
最後的Code就長醬~
var buffer = new System.IO.MemoryStream(); var setting = new System.Xml.XmlWriterSettings(); setting.Indent = true; setting.Encoding = new System.Text.UTF8Encoding(false);//取消前置識別字元 using (var write = System.Xml.XmlWriter.Create(buffer, setting)){ write.WriteStartElement("Transaction"); write.WriteAttributeString("Action", "AskData"); write.WriteEndElement(); }
沒有留言:
張貼留言