Search This Blog

Friday, January 7, 2011

Serializing/Deserializing XML files in C#

Suppose we start from a bare XML file we know nothing about. The easiest way to turn it to C# object is to use XSD executable from Microsoft SDK.

Mine xsd.exe was located in:
'c:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\xsd.exe'
There are 4 simple stept on how to use xsd and then Visual Studio to deserialize XML:

  1. Access Visual Studio command prompt from Start Menu > Program Files >Microsoft Visual Studio 2008 > Visual Studio Tools.
  2. From the current directory, type XSD.exe . This will list all the arguments and options for the said utility.
  3. To create a schema file from an existing *.xml file, type XSD.exe \path to your xml\filename.xml. The XSD file will be created on the current directory.
  4. To create a class file from the schema file, type XSD.exe \path to your schema\filename.xsd  /c . The class file will be created on the current directory.
In my case Config was the base class XSD tool has given me in output C# class:

            XmlSerializer s = new XmlSerializer(typeof(Config));
            Config newCfg;
            XmlReader r = XmlReader.Create("epuapcfg.xml");
            //TextReader r = new StreamReader("epuapcfg.xml");
            newCfg = (Config)s.Deserialize(r);

TIP1: Always remember that ALL classes must have parameterless constructors to be serialized!!!!


  1. xml is a very interesting language to be used and contain the data object model or abbreviated DOM.tutorial very good and hopefully can help me in building a web application thanks

  2. Swiming is the best exercise in summer and running in winter
    QU-IT & QU


If you like this post, please leave a comment :)