Microsoft provides code in its article, "How to serialize an object to XML by using Visual C#."
using System;
public class clsPerson
{
public string FirstName;
public string MI;
public string LastName;
}
class class1
{
static void Main(string[] args)
{
clsPerson p=new clsPerson();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
x.Serialize(Console.Out, p);
Console.WriteLine();
Console.ReadLine();
}
}
However, why doesn't the class, clsPerson, need to be marked with either the [DataContract] or [Serializable] attributes?
Because the XmlSerializer doesn't require those attributes to be placed on the class. Only BinaryFormatter and DataContractSerializer do. And for that matter, DataContractSerializer can do without.
See related question: Why is Serializable Attribute required for an object to be serialized
By design, XML serialization serializes public fields and public properties with get AND set accessor. The serialized type must also have a parameterless constructor. It's the only contract \o/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With