如何制作XML Serializable? [关闭]

问题描述 投票:1回答:1

我有一个我需要序列化的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]属性。

c# xml xml-parsing
1个回答
1
投票

Paste Special> Paste 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);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.