Detailed explanation of graphic code of Xml serialization

黄舟
Release: 2017-03-21 16:20:57
Original
1920 people have browsed it

XMLSerialization is the process of converting the public properties and fields of an object into XML format for storage or transmission. Deserialization recreates the original state of the object from the XML output. The most important class in XML serialization is the XmlSerializer class. Its most important methods are the Serialize and Deserialize methods, which are located in the System.Xml.Serializationnamespace.

1. Basic points of XML serialization

Before starting this section, let’s first look at the simplest example:

namespace 学习测试 { class Program { static void Main(string[] args) { Person p = new Person(1, "刘备", 176); string xmlString = ""; //xml序列化开始 using (MemoryStream ms = new MemoryStream()) { Type t = p.GetType(); XmlSerializer xml = new XmlSerializer(t); xml.Serialize(ms, p); byte[] arr = ms.ToArray(); xmlString = Encoding.UTF8.GetString(arr, 0, arr.Length); ms.Close(); } Console.WriteLine(xmlString); Console.ReadKey(); } } public class Person { //必须定义一个无参数构造函数,否则无法序列化(当然完全不写构造函数也是可以序列化的,因为有个默认的无参构造函数) public Person() { } public Person(int id, string name, int age) { Id = id; Name = name; //Age = age; } public int Id { get; set; } public string Name { get; set; } //私有字段 private int Age { get; set; } //只读属性 private int height; public int Height { get { return height; } } } }
Copy after login

The code output As follows:

From the above output, we can conclude that a parameterless constructor must be required, and the default one is also acceptable. But note that when the default parameterless constructor is overwritten, a parameterless constructor must be added. In addition, private properties and read-only properties cannot be serialized.

MoreNotes:

  1. To sequence The class must have a default constructor before it can be serialized using XmlSerializer;

  2. methods cannot be serialized;

  3. IndexIndex, private fields or read-only properties (except read-only collection properties) cannot be serialized;

  4. Classes that need to be serialized must have a parameterless constructor Function

  5. Enumeration variables can be serialized into strings. There is no need to use [XmlInclude]

  6. to export non-basic type objects. You must use [ XmlInclude] declared in advance. This rule recursively applies to the IsNullable parameter in the child element

  7. #If it is equal to false, it means that if the element is null, the element will not be displayed. (Valid for value types)

  8. Some classes cannot be XML serialized (even if [XmlInclude] is used)

  • IDictionary (such as HashTable)

  • The situation when a parent class object assigns a value to a subclass object

  • Circular references between objects

9. For objects that cannot be XML serialized, you may consider

  • using custom xml serialization (implementing IXmlSerializableinterface)

  • For classes that implement IDictionary, consider (1) replacing it with other collection classes; (2) encapsulating it with a class and providing Add and this functions

  • Some types need to be converted before they can be serialized to XML. For example, to XML serialize System.Drawing.Color, you can first use ToArgb() to convert it into an integer

  • If it is inconvenient to serialize an object with XML, you can consider using binary serialization. .

When you don’t want to serialize:

  • When you don’t want to serialize an attribute, use [System.Xml.Serialization.XmlIgnore] tag, can be used for attributes;

  • [NonSerializable] is invalid when applied to attributes, can be used for classes,structures, etc.

The default constructor is necessary because deserialization essentially uses reflection, and the default constructor is needed to instantiate the class. If the default constructor is removed, there will be no compilation problem, but an error will be reported when running.

Try not to initialize relatively large properties in the default constructor, which will cause the list to be initialized twice during deserialization: once in the default constructor, and then in deserialization Read from the XML document and execute it again.

2. Change the default value of XML serialization

Usually, in the process of XML serialization, many things are automatically generated. , such as XML namespace, encoding, etc.

1. Remove the default namespace and prefix:

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();   ns.Add("", "");     //第一个参数是前缀,第二个参数是命名空间     //然后在序列化的时候,指定自定义命名空间     xml.Serialize(ms, p, ns);
Copy after login

Output comparison:

Of course, this method can also be used to generate the custom namespace you want.

2. Remove the XML declaration:

public static string ObjectToXmlSerializer(Object Obj) { XmlWriterSettings settings = new XmlWriterSettings(); //去除xml声明 settings.OmitXmlDeclaration = true; settings.Encoding = Encoding.Default; System.IO.MemoryStream mem = new MemoryStream(); using (XmlWriter writer = XmlWriter.Create(mem, settings)) { //去除默认命名空间xmlns:xsd和xmlns:xsi XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer formatter = new XmlSerializer(Obj.GetType()); formatter.Serialize(writer, Obj, ns); } return Encoding.Default.GetString(mem.ToArray()); }
Copy after login
# at the top ## Output:

3、换行缩进

  settings.Indent = true;
Copy after login

  当XmlWriterSettings如此设置后,输出的XML为:

4、指定缩进字符

  settings.IndentChars = "--";
Copy after login

  输出如下:

  XmlWriterSettings更多设置属性如下:

成员 说明
CloseOutput 获取或设置一个值,该值指示在调用 Close 方法时,XmlWriter 是否还应该关闭基础流或 TextWriter。
Encoding 获取或设置要使用的文本编码的类型。
Indent 获取或设置一个值,该值指示是否缩进元素。
IndentChars 获取或设置缩进时要使用的字符串。
NamespaceHandling 获取或设置一个值,该值指示在编写 XML 内容时,XmlWriter 是否应移除重复的命名空间声明。 的默认是输出程序中出现的所有命名空间声明。
NewLineChars 获取或设置要用于分行符的字符串
NewLineHandling 获取或设置一个值,该值指示是否将输出中的分行符正常化。
NewLineOnAttributes 获取或设置一个值,该值指示是否将属性写入新行。
OmitXmlDeclaration 获取或设置一个值指示省略 XML 声明。
Encoding 获取或设置要使用的文本编码的类型。
Reset方法 重置以上属性

  http://msdn.microsoft.com/zh-cn/library/system.xml.xmlwritersettings(v=vs.110).aspx

三、实现序列化接口IXmlSerializable

  实现IXmlSerializable接口之后,我们能够自定义类序列化的方式。

  该接口包含3个方法:

XmlSchema GetSchema(); void ReadXml(XmlReader reader); void WriteXml(XmlWriter writer);
Copy after login

  简单示例:

namespace 自定义序列化 { class Program { static void Main(string[] args) { Person p = new Person(); p.Id = 1; p.Name = "刘备"; string str = ObjectToXmlSerializer(p); Console.WriteLine(str); Person p1 = ObjectToXmlDESerializer(str); Console.WriteLine("我的名字是:" + p1.Name); Console.ReadKey(); } //序列化Xml public static string ObjectToXmlSerializer(Object Obj) { string XmlString = ""; XmlWriterSettings settings = new XmlWriterSettings(); //去除xml声明 //settings.OmitXmlDeclaration = true; settings.Indent = true; settings.Encoding = Encoding.Default; using (System.IO.MemoryStream mem = new MemoryStream()) { using (XmlWriter writer = XmlWriter.Create(mem, settings)) { //去除默认命名空间xmlns:xsd和xmlns:xsi XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer formatter = new XmlSerializer(Obj.GetType()); formatter.Serialize(writer, Obj, ns); } XmlString = Encoding.Default.GetString(mem.ToArray()); } return XmlString; } //反序列化 public static T ObjectToXmlDESerializer(string str)where T : class { object obj; using (System.IO.MemoryStream mem = new MemoryStream(Encoding.Default.GetBytes(str))) { using (XmlReader reader = XmlReader.Create(mem)) { XmlSerializer formatter = new XmlSerializer(typeof(T)); obj = formatter.Deserialize(reader); } } return obj as T; } } public class Person { public int Id { get; set; } public string Name { get; set; } } public class PersonSerializer : IXmlSerializable { private Person p; public int Id { get; set; } public string Name { get; set; } #region IXmlSerializable 成员 System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() { throw new NotImplementedException(); } //如果这个方法默认则报:XML 文档(2, 2)中有错误。 void IXmlSerializable.ReadXml(XmlReader reader) { reader.ReadElementString("Person"); } void IXmlSerializable.WriteXml(XmlWriter writer) { writer.WriteElementString("Id", Id.ToString()); writer.WriteElementString("Name", Name); } #endregion } }
Copy after login

  输出如下:

  我们都知道,接口是不支持序列化的。下面来做个有用的示例,实现IList 的序列化与反序列化

namespace IList的序列化与反序列化 { class Program { static void Main(string[] args) { Woman w1 = new Woman() { Id = 1, Name = "貂蝉" }; Woman w2 = new Woman() { Id = 2, Name = "西施" }; List ListWoman = new List(); ListWoman.Add(w1); ListWoman.Add(w2); Person p = new Person(); p.Id = 1; p.Name = "刘备"; p.ListWoman = ListWoman; string str = ObjectToXmlSerializer(p); Console.WriteLine(str); Person p1 = ObjectToXmlDESerializer(str); Console.WriteLine("我的名字是:" + p1.Name + "我的老婆有:"); foreach (Woman w in p1.ListWoman) { Console.WriteLine(w.Name); } Console.ReadKey(); } //序列化Xml public static string ObjectToXmlSerializer(Object Obj) { string XmlString = ""; XmlWriterSettings settings = new XmlWriterSettings(); //去除xml声明 //settings.OmitXmlDeclaration = true; settings.Indent = true; settings.Encoding = Encoding.Default; using (System.IO.MemoryStream mem = new MemoryStream()) { using (XmlWriter writer = XmlWriter.Create(mem, settings)) { //去除默认命名空间xmlns:xsd和xmlns:xsi XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer formatter = new XmlSerializer(Obj.GetType()); formatter.Serialize(writer, Obj, ns); } XmlString = Encoding.Default.GetString(mem.ToArray()); } return XmlString; } //反序列化 public static T ObjectToXmlDESerializer(string str) where T : class { object obj; using (System.IO.MemoryStream mem = new MemoryStream(Encoding.Default.GetBytes(str))) { using (XmlReader reader = XmlReader.Create(mem)) { XmlSerializer formatter = new XmlSerializer(typeof(T)); obj = formatter.Deserialize(reader); } } return obj as T; } } public class Person : IXmlSerializable { public int Id { get; set; } public string Name { get; set; } public IList ListWoman { get; set; } #region IXmlSerializable 成员 System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() { throw new NotImplementedException(); } void IXmlSerializable.ReadXml(XmlReader reader) {        //一定要特别注意配对问题,否则很容易反序列化集合出现只能够读取第一个的情况 reader.ReadStartElement("Person"); Id = Convert.ToInt32(reader.ReadElementString("Id")); Name = reader.ReadElementString("Name"); //我也不知道为什么,复杂类型只能够另外定义一个,获得值之后再给原来的赋值 List ListWoman2 = new List(); reader.ReadStartElement("ListWoman"); while (reader.IsStartElement("Woman")) { Woman w = new Woman(); reader.ReadStartElement("Woman"); w.Id = Convert.ToInt32(reader.ReadElementString("Id")); w.Name = reader.ReadElementString("Name"); reader.ReadEndElement(); reader.MoveToContent(); ListWoman2.Add(w); } ListWoman = ListWoman2; reader.ReadEndElement(); reader.ReadEndElement(); } void IXmlSerializable.WriteXml(XmlWriter writer) {        //这里是不需要WriteStart/End Person的 writer.WriteElementString("Id", Id.ToString()); writer.WriteElementString("Name", Name); //有重载,想设置命名空间,只需在参数加上 writer.WriteStartElement("ListWoman"); foreach (Woman item in ListWoman) { PropertyInfo[] ProArr = item.GetType().GetProperties(); writer.WriteStartElement("Woman"); foreach (PropertyInfo p in ProArr) { writer.WriteElementString(p.Name, p.GetValue(item, null).ToString()); } writer.WriteEndElement(); } writer.WriteEndElement(); } #endregion } public class Woman { public int Id { get; set; } public string Name { get; set; } } }
Copy after login

  输出如下:

  以上代码是能够直接用于序列化数组的,也就是IList 的,下面在贴上两个序列化与反序列化IList 的方法:

//序列化Xml public static string ListToXmlSerializer(IList ListT) { XmlSerializer ser = new XmlSerializer(ListT.GetType()); System.IO.MemoryStream mem = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = false; settings.Encoding = Encoding.UTF8; XmlWriter writer = XmlWriter.Create(mem, settings); ser.Serialize(writer, ListT); writer.Close(); string strtmp = Encoding.UTF8.GetString(mem.ToArray()); return strtmp; } //反序列化Xml public static List XmlToListSerializer(Stream stream) { string XmlPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\OutLine\" + typeof(T).Name + ".xml"; using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8)) { XmlSerializer ser = new XmlSerializer(typeof(List)); var listsch = ser.Deserialize(sr); List reses = listsch as List; return reses; } }
Copy after login

  下面给出一个序列化与反序列化通过反射的复杂对象的示例:

using System.Linq.Expressions;namespace 控制台___学习测试 { class Program { static void Main(string[] args) { Woman w1 = new Woman() { Id = 1, Name = "貂蝉" }; Woman w2 = new Woman() { Id = 2, Name = "西施" }; List ListWoman1 = new List(); ListWoman1.Add(w1); ListWoman1.Add(w2); List ListPerson = new List(); Person p1 = new Person() { Id = 1, Name = "刘备", ListWoman = ListWoman1 }; Person p2 = new Person() { Id = 2, Name = "关羽", ListWoman = ListWoman1 }; Person p3 = new Person() { Id = 3, Name = "张飞", ListWoman = ListWoman1 }; ListPerson.Add(p1); ListPerson.Add(p2); ListPerson.Add(p3); string xml = ListToXmlSerializer(ListPerson); Console.WriteLine(xml); MemoryStream mem = new MemoryStream(Encoding.UTF8.GetBytes(xml)); List ListPerson2 = XmlToListSerializer(mem); Console.WriteLine(ListPerson2.Count); Console.WriteLine(ListPerson2[2].ListWoman[1].Name); Console.ReadKey(); } //序列化Xml public static string ListToXmlSerializer(IList ListT) { XmlSerializer ser = new XmlSerializer(ListT.GetType()); System.IO.MemoryStream mem = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; settings.Encoding = Encoding.UTF8; XmlWriter writer = XmlWriter.Create(mem, settings); ser.Serialize(writer, ListT); writer.Close(); string strtmp = Encoding.UTF8.GetString(mem.ToArray()); File.WriteAllText(@"D:\222.xml", strtmp); return strtmp; } //反序列化Xml public static List XmlToListSerializer(Stream stream) { using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8)) { XmlSerializer ser = new XmlSerializer(typeof(List)); var listsch = ser.Deserialize(sr); List reses = listsch as List; return reses; } } } public class Person : IXmlSerializable { public int Id { get; set; } public string Name { get; set; } public IList ListWoman { get; set; } #region IXmlSerializable 成员 System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() { throw new NotImplementedException(); } void IXmlSerializable.ReadXml(XmlReader reader) { //while (reader.Name == "Person") //{ reader.ReadStartElement("Person"); Id = Convert.ToInt32(reader.ReadElementString("Id")); Name = reader.ReadElementString("Name"); List newWomans = new List(); PropertyInfo[] ProArr = typeof(Woman).GetProperties(); reader.ReadStartElement("ListWoman"); while (reader.IsStartElement("Woman")) { Woman Item2 = new Woman(); reader.ReadStartElement("Woman"); foreach (PropertyInfo p in ProArr) { string str = reader.ReadElementString(p.Name); p.SetValue(Item2, Convert.ChangeType(str, p.PropertyType), null); } reader.ReadEndElement(); reader.MoveToContent(); newWomans.Add(Item2); } ListWoman = newWomans; reader.ReadEndElement(); reader.ReadEndElement(); } void IXmlSerializable.WriteXml(XmlWriter writer) { writer.WriteElementString("Id", Id.ToString()); writer.WriteElementString("Name", Name); writer.WriteStartElement("ListWoman"); foreach (Woman item in ListWoman) { PropertyInfo[] ProArr = item.GetType().GetProperties(); writer.WriteStartElement("Woman"); foreach (PropertyInfo p in ProArr) { if (p.GetValue(item, null) != null) { writer.WriteElementString(p.Name, p.GetValue(item, null).ToString()); } else { writer.WriteElementString(p.Name, ""); } } writer.WriteEndElement(); } writer.WriteEndElement(); } #endregion } public class Woman { public int Id { get; set; } public string Name { get; set; } } }
Copy after login

  以上代码输出:

  特别提示,一定要特别特别注意,ReadStartElement与ReadEndElement的问题,否则很容易出现反序列化集合时只能够读取第一个的情况。而对于序列化,如果WriteStartElement与WriteEndElement不匹配,出现的只是XML标签对不匹配的问题,没Read的时候那么坑。

四、XML特性

  有时,我们在序列化时想要自定义XML的结构,这时候就要用到我们的属性类了。属性类提供了很多特性供我们使用,以完成自定义序列化功能。

名称 描述
XmlAttribute 表示一个特性对象的集合,这些对象控制XmlSerializer如何序列化和反序列化对象
XmlArrayAttribute 指定XmlSerializer应将特定的类成员序列化为XML元素数组
XmlArrayItemAttribute 指定XmlSerializer可以放置在序列化数组中的派生类型
XmlArrayItemAttributes 表示XmlArrayItemAttribute对象的集合
XmlAttributeAttribute 指定XmlSerializer应将类成员作为XML特性序列化
XmlChoiceIdentifierAttribute 指定可以通过使用枚举来进一步消除成员的歧义
XmlElementAttribute 在XmlSerializer序列化或反序列化包含对象时,指示公共字段或属性表示XML元素
XmlElementAttributes 表示XmlElementAttribute的集合,XmlSerializer将其用于它重写序列化类的默认方式
XmlEnumAttribute 控制XmlSerializer如何序列化枚举成员
XmlIgnoreAttribute 指示XmlSerializer方法不序列化公共字段或公共读/写属性值
XmlIncludeAttribute 允许XmlSerializer在它序列化或反序列化对象时识别类型
XmlRootAttribute 控制视为XML根元素的属性目标的XML序列化
XmlTextAttribute 当序列化或反序列化时,想XmlSerializer指示应将此成员作为XML文本处理
XmlTypeAttribute 控制当属性目标由XmlSerializer序列化时生成的XML结构
XmlAnyAttributeAttribute 指定成员(返回XmlAttribute对象的数组的字段)可以包含XML属性
XmlAnyElementAttribute 指定成员可以包含对象,该对象表示在序列化或反序列化的对象中没有相应成员的所有XML元素
XmlAnyElementAttributes 表示XmlAnyElementAttribute对象的集合
XmlAttributeEventArgs 为UnKnowAttribute提供数据
XmlAttributeOverrides 允许你在使用XmlSerializer序列化或反序列化时重写属性、字段和类特性
XmlElementEventArgs 为UnknownElement事件提供数据
XmlNamespaceDeclarationsAttribute 指定目标属性、参数、返回值或类成员包含与XML文档中所用命名空间关联的前缀
XmlNodeEventArgs 为UnknownNode时间提供数据
XmlSerializer 将对象序列化到XML文档中和从XML文档中反序列化对象,XmlSerializer使你得以控制如何将对象编码到XML中
XmlSerializerNamespaces 包含XmlSerializer用于在XML文档实例中生成限定名的XML命名空间和前缀
XmlTypeMapping 包含从一种类型到另一种类型的映射

  下面仅仅给出两个简单示例:

namespace 学习测试 { [Serializable] public class Person { public Person() { } public int Id { get; set; } public string Name { get; set; } [XmlAttribute(DataType = "string")] public string Content { get; set; } [XmlIgnore] public int Age { get; set; } [XmlArray] [XmlArrayItem("Int32", typeof(Int32))] public IList ListInt { get; set; } } class Program { static void Main(string[] args) { IList list = new ArrayList(); list.Add(1); list.Add(2); list.Add(3); Person p = new Person(); p.Id = 1; p.Name = "刘备"; p.Age = 23; p.Content = "这是一个牛人"; p.ListInt = list; string strXml = ObjectToXmlSerializer(p); Console.WriteLine(strXml); //反序列化IList还有问题 //Person p2 = ObjectToXmlDESerializer(strXml); //Console.WriteLine(p2.Name); Console.ReadKey(); } //序列化 public static string ObjectToXmlSerializer(Object Obj) { string XmlString = ""; XmlWriterSettings settings = new XmlWriterSettings(); //去除xml声明 //settings.OmitXmlDeclaration = true; settings.Indent = true; settings.Encoding = Encoding.Default; using (System.IO.MemoryStream mem = new MemoryStream()) { using (XmlWriter writer = XmlWriter.Create(mem, settings)) { //去除默认命名空间xmlns:xsd和xmlns:xsi XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer formatter = new XmlSerializer(Obj.GetType()); formatter.Serialize(writer, Obj, ns); } XmlString = Encoding.Default.GetString(mem.ToArray()); } return XmlString; } //反序列化Xml public static T ObjectToXmlDESerializer(string str) where T : class { object obj; using (System.IO.MemoryStream mem = new MemoryStream(Encoding.Default.GetBytes(str))) { using (XmlReader reader = XmlReader.Create(mem)) { XmlSerializer formatter = new XmlSerializer(typeof(T)); obj = formatter.Deserialize(reader); } } return obj as T; } } }
Copy after login

2013/12/27 常遇错误记录:

反序列化错误提示:

1、XML 文档(2, 2)中有错误:

  报这个错误一般是由于序列化与反序列化的类型不一致:

XmlSerialize.Serialize(@"C:\Person.xml",person);   //person 是 Person类的对象var test = XmlSerialize.DeSerialize(typeof(Person), @"C:\Person.xml");
Copy after login

2014/08/12

2、XmlIgnore与NonSerialized的区别。

  1、XmlIgnore能作用于属性,NonSerialized只作用于字段。

  2、XmlIgnore对序列化与反序列化均有效,而NonSerialized只影响序列化,反序列化不管。(非百分百确定)

The above is the detailed content of Detailed explanation of graphic code of Xml serialization. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!