How to make an XML Serializable? [closed]

女生的网名这么多〃 提交于 2019-12-11 08:55:57

问题


I had an XML File that I needed to serialize. I used VS feature Paste Special->Convert XML to C# Classes feature and got the C# classes for that XML file.

The C# file for the XML has Multiple Classes as shown in the image below:

The generated C# of XML has the following structure

[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;
------
-----
}

I want to add the [serializable] attribute and go ahead with the serializing the whole XML. I am unable to add [serializable] attribute.


回答1:


The Paste Special > Paste Xml As Classes command already adds the SerializableAttribute the classes it creates so no need to add them yourself. You should be able to serialization straight away:

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);
        }
    }
}


来源:https://stackoverflow.com/questions/42413065/how-to-make-an-xml-serializable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!