Wednesday, March 26, 2008

The simplest way to store object to .xml file in c#.

The simplest way to implement xml serialization in c#:

1. Add attribute [Serializable] for all classes.

2. All public fields will be serialized.

3. If you want to store field as xml attribute add attribute [XmlAttribute("")].

[Serializable]
public class SubData
{
[XmlAttribute("")]
public int subDataAsAttribute;
public int subData;
public int SubProperty { get { return subDataAsAttribute + subData; } }
}
[Serializable]
public class Data
{
public int publicIntData;
internal int internalIntData;
protected int protectedIntData;
private int privateIntData;
public SubData subData;
public Data()
{
}
public Data(int publicIntData)
{
this.publicIntData = publicIntData;
}
}



4. Create objects XmlSerializer and TextWriter and store needed object to xml file:



string xmlFilePath = "data.xml";
XmlSerializer serializer = new XmlSerializer(typeof(Data));
using (TextWriter writer = new StreamWriter(xmlFilePath))
{
serializer.Serialize(writer, data);
}


5. To read the stored object use XmlSerializer and TextReader:


Data actualData;
using (TextReader reader = new StreamReader(xmlFilePath))
{
actualData = (Data) serializer.Deserialize(reader);
}
6. See sample of relevant xml file:


xmlScreen 


Reference:


XmlSerializer Class

No comments: