How to make an XML Serializable? [closed]

2019-07-29 04:32发布

问题:

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