Wednesday, April 07, 2010

XmlSerializer class for reading and writing XML.

There are many ways to read and write XML.

The advantage of the XmlSerializer class is that you can read and/or write XML with very little code. Most of the code required is simply the definition of the data. In other words, if our data is a list of Links consisting of a HREF or URL, a title and a category, then that data could be defined in the following manner:

public class LinkObject
{
     string ThisCategory;
     string ThisHRef;
     string ThisTitle;

     public string Category
     {
           get { return ThisCategory; }
           set { ThisCategory = value; }
     }

     public string HRef
     {
           get { return ThisHRef; }
           set { ThisHRef = value; }
     }

     public string Title
     {
           get { return ThisTitle; }
           set { ThisTitle = value; }
     }
}

Using the XmlSerializer class, we use Serialize.Deserialize to read the data and XmlSerializer.Serialize to write the data. An instance of the XmlSerializer class could be created using:

XmlSerializer Serializer = new XmlSerializer(typeof(LinkObjectsList));

Then the data could be written using:

TextWriter Writer = new StreamWriter(Filename);
Serializer.Serialize(Writer, LinksList);
Writer.Close();

Data could be read using:

TextReader Reader = new StreamReader(Filename);
LinksList = (LinkObjectsList)Serializer.Deserialize(Reader);
Reader.Close();

It is nearly that easy. Note that when the data is as simple of the above data, it is possible to read and write the data using a DataTable. If however the data is more complicated than what a single DataTable is capable of, then the XmlSerializer class can be easier (see below).

Note that the LinkObject class above represents one link. We are writing and reading a list of links, where list could be called an array or a collection or a table or something else. We can create a list of links using:

List<LinkObject> LinksList = new List<LinkObject>();

Read more: C# Corner

Posted via email from jasper22's posterous