C#对象转换为XML字符串和将Xml字符串转换为C#对象
1 using System.Xml.Serialization; 2 3 namespace ConsoleApplication4 4 { 5 [Serializable] 6 public struct Priority 7 { 8 public String Name; 9 public Boolean State; 10 public Priority(String name, Boolean State) 11 { 12 Name = name; 13 this.State = State; 14 } 15 } 16 [Serializable] 17 public class Person 18 { 19 public String Name{get;set;} 20 public Int32 Age { get; set; } 21 private List<Priority> data = new List<Priority>(); 22 public List<Priority> Data 23 { 24 get { return data; } 25 set { data = value; } 26 } 27 } 28 class Program 29 { 30 static void Main(string[] args) 31 { 32 Person p = new Person() 33 { 34 Name = "Job", 35 Age = 12 36 }; 37 p.Data.Add(new Priority("Token",true)); 38 p.Data.Add(new Priority("Hasen", false)); 39 40 //下面将一个对象序列化成一个Xml的字符串 41 XmlSerializer xs = new XmlSerializer(p.GetType()); 42 MemoryStream ms = new MemoryStream(); 43 xs.Serialize(ms, p);//将一个对象序列化成XML保存在内存流中 44 //获取内存流中的字符串 45 String XmlString = Encoding.UTF8.GetString(ms.ToArray()); 46 Console.WriteLine(XmlString); 47 Console.WriteLine("字符个数为:"+XmlString.Count()); 48 ms.Close(); 49 50 //下面将XML字符串反序列成C#对象 51 MemoryStream ms1 = new MemoryStream(Encoding.UTF8.GetBytes(XmlString)); 52 Person p1 = xs.Deserialize(ms1) as Person; 53 Console.WriteLine("Name:"+p1.Name +" Age:"+p1.Age +" Token:"+p1.Data[0].State); 54 ms1.Close(); 55 Console.ReadKey(); 56 } 57 } 58 }
运行效果为: