XML和实体类之间相互转换(序列化和反序列化)

字符串转换成xml文本

var xmlDoc = new XmlDocument();

  xmlDoc.LoadXml(xml);

List转换到Xml

// 生成List对象用于测试

List list1 = new List(3);

list1.Add(new Student() { Name = "okbase", Age = 10 });

list1.Add(new Student() { Name = "csdn", Age = 15 });

// 序列化

utf-16

using (StringWriter sw = new StringWriter())

            {

                XmlSerializer xz = new XmlSerializer(list1.GetType());

                xz.Serialize(sw,list1);

                xml = sw.ToString();

            }

Console.Write(xml);


utf-8

XmlSerializer xs = new XmlSerializer(list1.GetType());

            MemoryStream stream = new MemoryStream();

            XmlWriterSettings setting = new XmlWriterSettings();

            setting.Encoding = new UTF8Encoding(false);

            setting.Indent = true;

            using (XmlWriter writer = XmlWriter.Create(stream))

            {

              xs.Serialize(writer, list1);

            }

            xml =  Encoding.UTF8.GetString(stream.ToArray());


Xml转换到List


using (StringReader sr = new StringReader(xml))

                {

                    XmlSerializer xmldes = new XmlSerializer(typeof(List));

                    List list2 = (List)xmldes.Deserialize(sr);

                }

你可能感兴趣的:(XML和实体类之间相互转换(序列化和反序列化))