Table of Contents
1. Basic points of XML serialization" >1. Basic points of XML serialization
2. Change the default value of XML serialization" >2. Change the default value of XML serialization
三、实现序列化接口IXmlSerializable" >三、实现序列化接口IXmlSerializable
四、XML特性 " >四、XML特性 
Home Backend Development XML/RSS Tutorial Detailed explanation of graphic code of Xml serialization

Detailed explanation of graphic code of Xml serialization

Mar 21, 2017 pm 04:20 PM

 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.Serialization namespace.

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.

 More Notes:

  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<Person>(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<T>(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<T>的序列化与反序列化
{
    class Program
    {
        static void Main(string[] args)
        {
            Woman w1 = new Woman() { Id = 1, Name = "貂蝉" };
            Woman w2 = new Woman() { Id = 2, Name = "西施" };

            List<Woman> ListWoman = new List<Woman>();
            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<Person>(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<T>(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<Woman> 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<Woman> ListWoman2 = new List<Woman>();
            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<T>(IList<T> 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<T> XmlToListSerializer<T>(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<T>));
                var listsch = ser.Deserialize(sr);
                List<T> reses = listsch as List<T>;
                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<Woman> ListWoman1 = new List<Woman>();
            ListWoman1.Add(w1);
            ListWoman1.Add(w2);

            List<Person> ListPerson = new List<Person>();
            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<Person> ListPerson2 = XmlToListSerializer<Person>(mem);

            Console.WriteLine(ListPerson2.Count);

            Console.WriteLine(ListPerson2[2].ListWoman[1].Name);
            Console.ReadKey();
        }

        //序列化Xml
        public static string ListToXmlSerializer<T>(IList<T> 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<T> XmlToListSerializer<T>(Stream stream)
        {
            using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8))
            {
                XmlSerializer ser = new XmlSerializer(typeof(List<T>));
                var listsch = ser.Deserialize(sr);
                List<T> reses = listsch as List<T>;
                return reses;
            }
        }
    }

    public class Person : IXmlSerializable
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public IList<Woman> 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<Woman> newWomans = new List<Woman>();
            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<Person>(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<T>(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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Convert XML data to CSV format in Python Convert XML data to CSV format in Python Aug 11, 2023 pm 07:41 PM

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

Using Python to implement data verification in XML Using Python to implement data verification in XML Aug 10, 2023 pm 01:37 PM

Using Python to implement data validation in XML Introduction: In real life, we often deal with a variety of data, among which XML (Extensible Markup Language) is a commonly used data format. XML has good readability and scalability, and is widely used in various fields, such as data exchange, configuration files, etc. When processing XML data, we often need to verify the data to ensure the integrity and correctness of the data. This article will introduce how to use Python to implement data verification in XML and give the corresponding

Convert POJO to XML using Jackson library in Java? Convert POJO to XML using Jackson library in Java? Sep 18, 2023 pm 02:21 PM

Jackson is a Java-based library that is useful for converting Java objects to JSON and JSON to Java objects. JacksonAPI is faster than other APIs, requires less memory area, and is suitable for large objects. We use the writeValueAsString() method of the XmlMapper class to convert the POJO to XML format, and the corresponding POJO instance needs to be passed as a parameter to this method. Syntax publicStringwriteValueAsString(Objectvalue)throwsJsonProcessingExceptionExampleimp

In Java, how can we serialize a list of objects using flexjson? In Java, how can we serialize a list of objects using flexjson? Sep 05, 2023 pm 11:09 PM

Flexjson is a lightweight library for serializing and deserializing Java objects to and from JSON format. We can serialize a list of objects using the serialize() method of the JSONSerializer class. This method performs shallow serialization on the target instance. We need to pass a list of objects of list type as a parameter to the serialize() method. Syntax publicStringserialize(Objecttarget) example importflexjson.JSONSerializer;importjava.util.*;publicclassJsonSerial

How does Java serialization affect performance? How does Java serialization affect performance? Apr 16, 2024 pm 06:36 PM

The impact of serialization on Java performance: The serialization process relies on reflection, which will significantly affect performance. Serialization requires the creation of a byte stream to store object data, resulting in memory allocation and processing costs. Serializing large objects consumes a lot of memory and time. Serialized objects increase load when transmitted over the network.

Parsing XML documents with namespaces using Python Parsing XML documents with namespaces using Python Aug 09, 2023 pm 04:25 PM

Use Python to parse XML documents with namespaces. XML is a commonly used data exchange format that can adapt to various application scenarios. When processing XML documents, sometimes you encounter situations with namespaces. Namespace can prevent the conflict of element names in different XML documents and improve the flexibility and scalability of XML. This article will introduce how to use Python to parse XML documents with namespaces and give corresponding code examples. First, we need to import xml.et

See all articles