如何制作XML Serializable?

时间:2017-02-23 10:28:49

标签: c# xml xml-parsing

我有一个需要序列化的XML文件。我使用VS功能Paste Special->将XML转换为C#Classes功能,并获得该XML文件的C#类。

XML的C#文件有多个类,如下图所示:

enter image description here

生成的XML的C#具有以下结构

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://example.com/633")]
        [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://example.com/633", IsNullable = false) ]

        public partial class FlightPlan
        {

            private FlightPlanM633Header m633HeaderField;

            private FlightPlanM633SupplementaryHeader m633SupplementaryHeaderField;
------
-----
}

我想添加[serializable]属性并继续序列化整个XML。我无法添加[serializable]属性。

1 个答案:

答案 0 :(得分:1)

Paste Special>粘贴Xml As Classes 命令已经添加了SerializableAttribute它创建的类,因此无需自己添加它们。您应该能够立即进行序列化:

using System;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var serializer = new XmlSerializer(typeof(FlightPlan));

            // Deserialize
            FlightPlan o = (FlightPlan)
                serializer.Deserialize(new StreamReader("source.xml"));

            // Serialize
            serializer.Serialize(new StreamWriter("Out.xml"), o);
        }
    }
}