DataContractSerializer对象
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public char Gender { get; set; }
}
Person
private async void Button_Click(object sender, RoutedEventArgs e)
{
Person zhang = new Person();
zhang.Id = ;
zhang.Name = "letter zhang";
zhang.Age = ;
zhang.Gender = '男';
//XML序列化工具
DataContractSerializer serializer = new DataContractSerializer(zhang.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, zhang);
ms.Position = ;
//读取流中的数据
using (var reader = new StreamReader(ms))
{
var result = await reader.ReadToEndAsync();
System.Diagnostics.Debug.WriteLine(result);
}
}
}
XmlSerializer对象
private async void Button_Click(object sender, RoutedEventArgs e)
{
Person zhang = new Person();
zhang.Id = ;
zhang.Name = "letter zhang";
zhang.Age = ;
zhang.Gender = '男';
var serializer = new XmlSerializer(zhang.GetType());
var settings = new XmlWriterSettings
{
Indent = true,
NewLineChars = "\r\n",
Encoding = Encoding.UTF8,
IndentChars = " "
};
using (var stream = new MemoryStream())
{
using (XmlWriter writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, zhang);
}
stream.Position = ;
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
var result = await reader.ReadToEndAsync();
System.Diagnostics.Debug.WriteLine(result);
}
}
}