read class object in xml in csharp

To read a class object from an XML file, you can use serialization and deserialization. The following code shows an example of how to do this:

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

// The class you want to serialize and deserialize
[Serializable]
public class MyClass
{
    public int MyInt { get; set; }
    public string MyString { get; set; }
}

// Serialization method
public void SerializeToXml(MyClass obj, string filename)
{
    XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
    using (TextWriter writer = new StreamWriter(filename))
    {
        serializer.Serialize(writer, obj);
    }
}

// Deserialization method
public MyClass DeserializeFromXml(string filename)
{
    XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
    using (TextReader reader = new StreamReader(filename))
    {
        return (MyClass)serializer.Deserialize(reader);
    }
}

// Usage examples
MyClass obj = new MyClass { MyInt = 42, MyString = "hello" };
string filename = "myobject.xml";

// Serialize object to XML
SerializeToXml(obj, filename);

// Deserialize object from XML
MyClass deserializedObj = DeserializeFromXml(filename);
1022 chars
41 lines

In the SerializeToXml method, an instance of the XmlSerializer class is created with the type of the MyClass class. The method then uses a TextWriter to write the serialized object to a file.

In the DeserializeFromXml method, an instance of the XmlSerializer class is again created with the type of the MyClass class. The method then uses a TextReader to read the serialized object from the file and deserialize it.

Note that the MyClass class is marked with the [Serializable] attribute, which makes it possible to serialize and deserialize instances of the class.

gistlibby LogSnag