xml序列化与反序列化
XmlConfig.cs
namespace Model { [ Serializable] public class XmlConfig { [ XmlElement] public List <Class1> Class1; [ XmlElement] public List <Class2> Class2; [ XmlIgnore] private static XmlConfig list; public static void SetModelList( XmlConfig zlist) { list = zlist; } public static XmlConfig GetModelList() { if (list == null ) { list = new XmlConfig (); } return list; } public XmlConfig(){} } [ Serializable] public class Class2 { [ XmlElement] public List <Class3> Class3; public Class2() { } [ XmlAttribute] public string Name;//名称 } [ Serializable] public class Class3 { publicClass3() { } [ XmlAttribute] } }
XmlSerialiaze.cs
namespaceModel { public class XmlSerialiaze { //序列化 public static void Serialiaze() { XmlConfig p = XmlConfig .GetModelList();
Class1 tb = new Class1(); Class1 temp = p.Class1[0]; tb.Name = temp.Name; p.Class1.Add(tb); //添加 tb.Class2= new List <Class2>(); Class2 cb = new Class2(); Class2 cool = temp.Class2[0]; tb.Class2.Add(cb);
XmlSerializer xs = new XmlSerializer( typeof(XmlConfig )); Stream stream = new FileStream( AppDomain.CurrentDomain.BaseDirectory + "XmlConfig.xml" , FileMode.Create, FileAccess .Write, FileShare.ReadWrite); xs.Serialize(stream, p); stream.Close(); } //反序列化 //XmlConfig p; public static void Deserialize() { XmlSerializer xs = new XmlSerializer( typeof(XmlConfig )); Stream stream = new FileStream( AppDomain.CurrentDomain.BaseDirectory + "XmlConfig.xml" , FileMode.Open, FileAccess .Read, FileShare.ReadWrite); XmlConfig p = (XmlConfig )xs.Deserialize(stream); XmlConfig.SetModelList(p); } } }
一分辛苦一分才