xml 格式如下:
<?xml version="1.0" encoding="utf-8" ?> <Persons> <Person Name="张三" Sex="男" Age="18" Height ="180" ></Person> <Person Name="李四" Sex="男" Age="21" Height ="170" ></Person> <Person Name="王五" Sex="女" Age="12" Height ="120" ></Person> <Person Name="赵六" Sex="男" Age="58" Height ="160" > <Children> <Child Name="孩子一" Sex="2"></Child> <Child Name="孩子二" Sex="5"></Child> </Children> </Person> </Persons>
为了方便起见,以下略去读取xml文件以及写入生产xml文件,直接将以上xml文件写在cs文件中。
namespace XML序列化 { class MyXmlOptions { public Persons per { get; set; } public string xmlString { get; set; } public MyXmlOptions() { //读取本地 xml 文件内容 xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<Persons>" + " <Person Name=\"张三\" Sex=\"男\" Age=\"18\" Height =\"180\" ></Person> " + " <Person Name=\"李四\" Sex=\"男\" Age=\"21\" Height =\"170\" ></Person> " + " <Person Name=\"王五\" Sex=\"女\" Age=\"12\" Height =\"120\" ></Person> " + " <Person Name=\"赵六\" Sex=\"男\" Age=\"58\" Height =\"160\" > " + " <Children>" + " <Child Name=\"孩子一\" Sex=\"2\"></Child>" + " <Child Name=\"孩子二\" Sex=\"5\"></Child>" + " </Children>" + " </Person>" + "</Persons>"; } public string XmlDeserialize() { if (per != null) { StringBuilder sb = new StringBuilder(5000); XmlSerializer ser = new XmlSerializer(typeof(Persons)); using (TextWriter writer = new StringWriter(sb)) { ser.Serialize(writer, per); return writer.ToString(); } } else { return "实体对象不存在,饭序列化失败"; } } public void XmlSerialize() { XmlSerializer ser = new XmlSerializer(typeof(Persons)); using (TextReader reader = new StringReader(xmlString)) { per = (Persons)ser.Deserialize(reader); } } } }
客户端代码如下:
static void Main(string[] args) { MyXmlOptions option = new MyXmlOptions(); option.XmlSerialize(); Console.WriteLine(option.xmlString); Console.WriteLine(option.XmlDeserialize()); Console.ReadKey(); }
为了使 xml 能够序列化为 实体对象,并且可以反序列化,Poersons 实体 根据xml结构设置如下:
namespace XML序列化 { [XmlRoot("Persons", IsNullable = false)] public class Persons { [XmlElement("Person")] public List<Person> Person; } public class Person { [XmlAttribute("Name")] public string Name { get; set; } [XmlAttribute("Sex")] public string Sex { get; set; } [XmlAttribute("Age")] public string Age { get; set; } [XmlAttribute("Height")] public string Height { get; set; } [XmlElement("Children")] public Children Children; } public class Children { [XmlElement("Child")] public List<Child> Child; } public class Child { [XmlAttribute("Name")] public string Name { get; set; } [XmlAttribute("Sex")] public string Sex { get; set; } } }