XML序列化與反序列化
阿新 • • 發佈:2018-12-11
將Object序列化為XML檔案
[Serializable]
public class Person
{
public string Name{get;set;}
public bool Sex{get;set;}
}
class Porgram
{
public static void SerializeToXml<T>(object obj,string path)
{
FileStream xmlFile = new FileStream(path,FileMode.OpenOrCreate);
XmlSerializer xml = new XmlSerializer(typeof(T));
try
{
xml.Serialize(xmlFile,obj);
xmlFile.Close();
}catch
{
throw;
}
}
static void Main(string[] args)
{
Person a = new Person();
a.name = "Gets";
a. age = false;
SerializeToXml<Person>(a,$"D:/123.xml");
}
}
將XML檔案轉反序列化成Object物件
class Porgram
{
public static T DeserializeToObject<T>(string path)
{
try
{
FileStream xmlFile = new FileStream(path, FileMode.Open);
XmlSerializer xml = new XmlSerializer(typeof(T));
T t = (T)xml.Deserialize(xmlFile);
xmlFile.Close();
return t;
}catch
{
throw;
}
}
static void Main(string[] args)
{
var a = DeserializeToObject<Person>($"D:/123.xml");
}
}
XML檔案的序列化和反序列化
public class Student: SerializableConfig
{
[XmlAttribute(Namespace = "http://www.cpandl.com")]
public string GroupName;
[XmlAttribute(DataType = "base64Binary")]
public Byte[] GroupNumber;
[XmlAttribute(DataType = "date", AttributeName = "CreationDate")]
public DateTime Today;
[XmlAttribute]
public string Name { get; set; }
public List<College> Coll { get; set; }
public Student()
{
Coll = new List<College>();
}
}
public class College
{
[XmlAttribute]
public string ID { get; set; }
[XmlAttribute]
public string Age { get; set; }
}
//---------------------------------------------------------------------
static void Main(string[] args)
{
Student st = new Student();
st.GroupName = ".Net";
Byte[] hexByte = new Byte[2] { Convert.ToByte(100), Convert.ToByte(50) };
st.GroupNumber = hexByte;
DateTime date = new DateTime(2001, 1, 1);
st.Today = date;
st.Name = "Kkarot";
st.Coll.Add(new College() { Age = "11", ID = "10245412" });
st.Coll.Add(new College() { Age = "KK", ID = "CC" });
st.SerializeObject("kakarot.xml");
Student s = new Student();
s.Load("kakarot.xml");
Console.ReadKey();
}
SerializableConfig類
public class SerializableConfig
{
public void Load(string filename)
{
Stream fstream = new FileStream(filename, FileMode.Open);
XmlSerializer xml = new XmlSerializer(GetType());
var obj = xml.Deserialize(fstream);
PropertyInfo[] pros = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
// 表示當前 System.Type 的匹配指定繫結約束的所有屬性的 System.Reflection.PropertyInfo 物件陣列
foreach (var p in pros)
{
if (p.CanWrite && p.GetCustomAttribute<XmlIgnoreAttribute>() == null)
{
var obj_item = p.GetValue(obj); //返回指定物件的屬性值
p.SetValue(this, obj_item); //設定指定物件的屬性值
}
}
fstream.Close();
}
public void SerializeObject(string filename)
{
XmlSerializer my = new XmlSerializer(GetType());
TextWriter writer = new StreamWriter(filename);
my.Serialize(writer, this);
writer.Close();
}
}