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);
            r.Close();


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

2 comments:

  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

    ReplyDelete
  2. How are you Howard Howard Howard actions for a Smart Bowl victorious these days it's going well I had been looking improved adult. From I stumbled there was the work day Diane arrived. Which he doesn t have lots of of those solutions. Good thing is we as players are not employed by a club. I can walk right now out of the door and go onto vacation if I want to. Nobody is going to stop me.

    She was married to Jim J. Jones Best Yeezys Sr., who passed away MK Outlet Online in 2001. They had one child, the late Jim J. You can tell just by the title of the Jordan Shoes For Sale entry Coach Outlet Online that we're not heading Cheap Michael Kors Handbags anywhere good with this one. Yup, throughout history there are those who Nike Air Force 1 Cheap Outlet believed the key to good health (and terrible body odor) was wallowing in one's own excretions. It was said to cure an endless list of ailments and promote good health if Coach Outlet Clearance Sale drank, was applied to Ray Ban Outlet the skin and yes some even used it to give themselves (turn away now weak of heart) a nice bracing urine enema...

    ReplyDelete

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