var serializer = new XmlSerializer(typeof(SomeSerializableObject)); var memoryStream = new MemoryStream(); var streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8); serializer.Serialize(streamWriter, entry); byte[] utf8EncodedXml = memoryStream.ToArray();
以上基本可以用于序列化的可用形式,可以指定编码格式。
将xml转byte[]类型,方便下载使用。
XmlDocument xmldoc = new XmlDocument(); using(StringWriter wr = new StringWriter) { XmlSerializer xz = new XmlSerializer(类.GetType()); xz.Serialize(wr,类); xmldoc.LoadXml(wr.ToString()); byte[] download = System.Text.Encoding.Default.GetBytes(xmldoc.OuterXml); }
反序列化
var serializer = new XmlSerializer(typeof(SomeSerializableObject)); using(var memStm = new MemoryStream()) using(var xw = XmlWriter.Create(memStm)) { serializer.Serialize(xw, entry); var utf8 = memStm.ToArray(); }