save class object in xml in csharp

To save a class object in XML in c#, we can make use of object serialization. Serialization is the process of converting an object into a format that can be stored or transmitted. Here are the steps to save a class object in XML in c#:

Step 1: Add the [Serializable] attribute to the class that you want to serialize.

main.cs
[Serializable]
public class MyClass
{
    public string Name { get; set; }
    public int Age { get; set; }
}
110 chars
7 lines

Step 2: Create an instance of the class and populate its properties.

main.cs
var myClass = new MyClass
{
    Name = "John Doe",
    Age = 30
};
67 chars
6 lines

Step 3: Create an instance of the XmlSerializer class and pass it the type of the class.

main.cs
var serializer = new XmlSerializer(typeof(MyClass));
53 chars
2 lines

Step 4: Create a FileStream object to write the XML file.

main.cs
var fileStream = new FileStream("myfile.xml", FileMode.Create);
64 chars
2 lines

Step 5: Call the Serialize method of the XmlSerializer object and pass it the fileStream object and the object to serialize.

main.cs
serializer.Serialize(fileStream, myClass);
43 chars
2 lines

Step 6: Close the FileStream object.

main.cs
fileStream.Close();
20 chars
2 lines

This will save the MyClass object in an XML format in the myfile.xml file. You can then deserialize the XML back into an instance of the MyClass using the XmlSerializer.Deserialize method.

gistlibby LogSnag