Wednesday, February 18, 2009

C#: Deserialising XML files

If, for example, you have a books.xml file like this:
<books xsi="....">
  <bookinfo>
    <isbn>0596009305</isbn>
    <author>Bill Bosan</author>
    <title>All About Bulbs</title>
    <price>5.99</price>
    <description>Just when you thought...</description>
  </bookinfo>
  ....
</books>
and you wanted to read it into a list of objects in your .CS file.

First, you need to create a BookInfo class. For example:

public class BookInfo {
private string _id;
private string _author;
private string _title;
private decimal _price;
private string _description;


public string Isbn {
get { return _id; }
set { _id = value; }
}
public string Author {

...
}
}

Then, in your main code you would do something like this:

private void ReadXml(string filename) {
List _catalog;
string fullPath = HttpContext.Current.Server.MapPath(filename);
if (File.Exists(fullPath) == false)
return;
XmlSerializer serializer = new XmlSerializer(typeof(List));
using (FileStream stream = File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
_catalog = (List)serializer.Deserialize(stream);
}

}

Voila!

No comments: