1.只有公共的属性和公共的字段才能被序列化,即使头上不加任何的Attribute.(本地化是这样的,网络传输没有研究)
2.公共属性或者公共字段头上加XElement 和Xattirbtue 是来标记该属性或字段是元素还是属性的。如果什么也没有标,则默认是元素。
3.网络传输,类头上要加上Serializble.
4.要序列化的类必须有个无参的构造函数,如果没有显示的写一个构造函数,则系统会默认给创建一个无参的构造函数。如果自己手写了一个构造函数,则系统就不给建了,所以如果自己建立的构造函数是有参数的,需要再建立一个无参数的构造函数,否则会报错。
5.如果对元素进行排序,可以按照声明的顺序,也可以通过 头上的attibute加order=int 来实现。但是需要注意一个元素加了order,其他的元素也需要加order。否则会在声明序列化器的时候报错。
6.建议最好写上XElement和XAttribute. 如果不改名字,可以直接写一个[XmlElement]
下面看例子:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace xmlSerializeTest { [Serializable] public class BaseInfo { private List<Person> plist = new List<Person>(); [XmlElement] public List<Person> Plist { get { return plist; } set { plist = value; } } } }
下面的一个node
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace xmlSerializeTest { public class Person { private string name = "zzz"; private int age; //public bool sex; //public int floor = 9; public Person(string strName)//构造函数 { } public Person() { } [XmlElement(ElementName = "Books",Order =2)] public List<Books> bookList = new List<Books>(); [XmlElement(Order = 1)] public string Name { get { return name; } set { name = value; } } [XmlAttribute(AttributeName = "myAge")] public int Age { get { return age; } set { age = value; } } } }
最后的末节点:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace xmlSerializeTest { public class Books { } }
调用:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using xmlSerializeTest; namespace Test { class Program { static void Main(string[] args) { Books bs1 = new Books(); Books bs2 = new Books(); Person p1 = new Person(); p1.bookList.Add(bs1); p1.bookList.Add(bs2); BaseInfo b1 = new BaseInfo(); b1.Plist.Add(p1); BaseInfo a = MyXmlDeserialize<BaseInfo>(@"C:\2.xml"); MyXmlSerializeAndsave<BaseInfo>(b1, @"C:\2.xml"); Console.WriteLine(MyXmlSerialize<BaseInfo>(b1)); Console.ReadKey(); } public static bool MyXmlSerializeAndsave<T>(T obj, string savePath) { try { XmlSerializer xmlserializer = new XmlSerializer(typeof(T)); using (StreamWriter swriter = new StreamWriter(savePath)) { xmlserializer.Serialize(swriter, obj); } } catch { return false; } return true; } public static string MyXmlSerialize<T>(T obj) { string s = string.Empty; try { using (StringWriter sw = new StringWriter()) { XmlSerializer serializer = new XmlSerializer(typeof(T)); serializer.Serialize(sw, obj); s = sw.ToString(); } } catch { } return s; } public static T MyXmlDeserialize<T>(string xmlPath) { if (File.Exists(xmlPath)) { //read file to memory StreamReader stream = new StreamReader(xmlPath); //declare a serializer XmlSerializer serializer = new XmlSerializer(typeof(T)); try { //Do deserialize return (T)serializer.Deserialize(stream); } //if some error occured,throw it catch (InvalidOperationException error) { throw error; } //finally close all resourece finally { //close the reader stream stream.Close(); //release the stream resource stream.Dispose(); } } //File not exists else { //throw data error exception throw new InvalidDataException("Can not open xml file,please check is file exists."); } } } }
再看看大师写的:
public static class XMLDeserializerHelper { /// <summary> /// Deserialization XML document /// </summary> /// <typeparam name="T">>The class type which need to deserializate</typeparam> /// <param name="xmlPath">XML path</param> /// <returns>Deserialized class object</returns> public static T Deserialization<T>(string xmlPath) { //check file is exists in case if (File.Exists(xmlPath)) { //read file to memory StreamReader stream = new StreamReader(xmlPath); //declare a serializer XmlSerializer serializer = new XmlSerializer(typeof(T)); try { //Do deserialize return (T)serializer.Deserialize(stream); } //if some error occured,throw it catch (InvalidOperationException error) { throw error; } //finally close all resourece finally { //close the reader stream stream.Close(); //release the stream resource stream.Dispose(); } } //File not exists else { //throw data error exception throw new InvalidDataException("Can not open xml file,please check is file exists."); } } /// <summary> /// Serializate class object to xml document /// </summary> /// <typeparam name="T">The class type which need to serializate</typeparam> /// <param name="obj">The class object which need to serializate</param> /// <param name="outPutFilePath">The xml path where need to save the result</param> /// <returns>run result</returns> public static bool Serialization<T>(T obj, string outPutFilePath) { //Declare a boolean value to mark the run result bool result = true; //Declare a xml writer XmlWriter writer = null; MemoryStream ms = new MemoryStream(); try { //create a stream which write data to xml document. writer = XmlWriter.Create(outPutFilePath, new XmlWriterSettings { //set xml document style - auto create new line Indent = true, }); } //if some error occured,throw it catch (ArgumentException error) { result = false; throw error; } //declare a serializer. XmlSerializer serializer = new XmlSerializer(typeof(T)); try { //Serializate the object serializer.Serialize(writer, obj); } //if some error occured,throw it catch (InvalidOperationException error) { result = false; throw error; } //At finally close all resource finally { //close xml stream writer.Close(); } return result; } public static string SerializationWithoutNameSpaceAndDeclare<T>(T obj) { //Declare a boolean value to mark the run result string result = string.Empty; //Declare a xml writer XmlWriter writer = null; XmlSerializerNamespaces nameSpace; MemoryStream ms = new MemoryStream(); try { //create a stream which write data to xml document. writer = XmlWriter.Create(ms, new XmlWriterSettings { //set xml document style - auto create new line Indent = true, //set xml has no declaration OmitXmlDeclaration = true, DoNotEscapeUriAttributes = true, NamespaceHandling = NamespaceHandling.OmitDuplicates }); nameSpace = new XmlSerializerNamespaces(); nameSpace.Add("", ""); } //if some error occured,throw it catch (ArgumentException error) { throw error; } //declare a serializer. XmlSerializer serializer = new XmlSerializer(typeof(T)); try { //Serializate the object serializer.Serialize(writer, obj, nameSpace); return Encoding.UTF8.GetString(ms.GetBuffer()); } //if some error occured,throw it catch (InvalidOperationException error) { throw error; } //At finally close all resource finally { //close xml stream writer.Close(); ms.Close(); } } /// <summary> /// Serializate class object to string /// </summary> /// <typeparam name="T">The class type which need to serializate</typeparam> /// <param name="obj">The class object which need to serializate</param> /// <param name="outPutFilePath">The xml path where need to save the result</param> /// <returns>run result</returns> public static string Serialization<T>(T obj) { //Declare a boolean value to mark the run result string result = string.Empty; //Declare a MemoryStream to save result MemoryStream stream = null; try { //create a memorystream which write data to memory. stream = new MemoryStream(); } //if some error occured,throw it catch (ArgumentException error) { throw error; } //declare a serializer. XmlSerializer serializer = new XmlSerializer(typeof(T)); try { //Serializate the object serializer.Serialize(stream, obj); result = Encoding.UTF8.GetString(stream.ToArray()); } //if some error occured,throw it catch (InvalidOperationException error) { throw error; } //At finally close all resource finally { //close xml stream stream.Close(); } return result; } }