save a class object in xml in csharp

To save a class object in XML in C#, you can use serialization. Serialization is the process of converting an object into a format that can be stored and reconstructed later.

Here's an example of how to save a class object in an XML file using serialization:

main.cs
using System.Xml.Serialization;
using System.IO;

// Create an instance of your class
MyClass myObject = new MyClass("someValue", 123);

// Create an XmlSerializer object
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));

// Create a FileStream object to write the XML file
FileStream fileStream = new FileStream("myObject.xml", FileMode.Create);

// Call the Serialize method of the XmlSerializer object to write the object to the file
serializer.Serialize(fileStream, myObject);

// Close the FileStream object
fileStream.Close();
546 chars
18 lines

In this example, we first create an instance of the MyClass class. Next, we create an XmlSerializer object, passing in the type of the class we want to serialize. We then create a FileStream object, specifying the filename and FileMode.Create to create a new file. Finally, we call the Serialize method of the XmlSerializer object, passing in the FileStream and the object to serialize. This writes the serialized object to the file. We then close the FileStream object.

Your MyClass should be decorated with [Serializable] attribute because XmlSerializer uses reflection to serialize the object. If serialization does not recognize a field, it will not be written to XML.

gistlibby LogSnag