本文主要是介绍C#序列化和反序列化XML -- XmlSerializer类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C#序列化和反序列化XML -- XmlSerializer类
- XmlSerializer类的使用 -- 单级节点
- XmlSerializer类的使用 -- 多级节点
- XmlSerializer类的使用 -- 节点属性
XmlSerializer类的使用 – 单级节点
using System;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApp2
{public class People{public int iAge { get; set; } = 50;public int iGender { get; set; } = 5;}class Program{static void Main(string[] args){String szPath = @"E:\\ConsoleApp2\\TestNode.xml";People data = new People();XmlSerializer xmlserializer = new XmlSerializer(typeof(People));//把People的成员变量以节点的形式写到xml中using (TextWriter writer = new StreamWriter(szPath, false, Encoding.UTF8)) //XML若不存在,创建XML{xmlserializer.Serialize(writer, data);}//从XML中读出节点值,并初始化给People的成员using (TextReader reader = new StreamReader(szPath, Encoding.UTF8)){People people = (People)(xmlserializer.Deserialize(reader));}}}
}
- 生成XML,内容:
XmlSerializer类的使用 – 多级节点
using System;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApp2
{public class People{public int id { get; set; } = 0;public int iAge { get; set; } = 0;public String szGender { get; set; } = "无";}public class listPeoples{public List<People> listPeople = new List<People>();}class Program{static void Main(string[] args){String szPath = @"E:\\ConsoleApp2\\TestNode.xml";listPeoples data = new listPeoples();People people1 = new People { id = 0, iAge = 10, szGender = "男"};People people2 = new People { id = 1, iAge = 20, szGender = 女"};data.listPeople.Add(new People());data.listPeople.Add(people1);data.listPeople.Add(people2);XmlSerializer xmlserializer = new XmlSerializer(typeof(listPeoples));//写到xml中using (TextWriter writer = new StreamWriter(szPath, false, Encoding.UTF8)){xmlserializer.Serialize(writer, data);}//从XML中读出using (TextReader reader = new StreamReader(szPath, Encoding.UTF8)){listPeoples obj = (listPeoples)(xmlserializer.Deserialize(reader));}}}
}
- 生成XML,内容:
XmlSerializer类的使用 – 节点属性
- 只需要在public类型变量的前面加上 [XmlAttribute],可以指定为属性
public class People{[XmlAttribute] public int id { get; set; } = 0;[XmlAttribute] public int iAge { get; set; } = 0;[XmlAttribute] public String szGender { get; set; } = "无";}
- 在XmlSerializer类的使用 – 多级节点 示例中添加属性后生成XML内容:
注意:
- private 属性将不会被序列化
- 打上[XmlIgnore]标签的public属性不会被序列化
- 枚举类型的属性,序列化前一定要赋值,否则会序列化失败
- 不打标签,默认打[XmlElement]标签,指明是节点
这篇关于C#序列化和反序列化XML -- XmlSerializer类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!