Tuesday, September 8, 2009

How to convert XML file in to a class file using c#?

The quick way is to use tools such as xsd.exe or XsdObjectGen.exe.

These tools allow you to quickly generate C# or VB classes from an xsd file.

Here’s what to do:
1) Open an xml file in Visual Studio
2) Create an xsd schema. (’XML\Create Schema’)
3) If necessary, edit the schema file
4) Open a Visual Studio command window and run one of the tools
5) Edit the generate classes (if necessary)

Example:
Code:

C:\projects\myproject\xsd.exe MyXmlClass.xsd /classes /n:CG.MyNamespace

The above command will generate a MyXmlClass.cs file that you include in your project.

To load up the class, it’s as easy as:
Code:

XmlSerializer serializer = new XmlSerializer( typeof( MyXmlClass ) ); using( XmlReader reader = XmlReader.Create( file ) ) { MyXmlClass myXmlClass = ( MyXmlClass )serializer.Deserialize( reader ); }

Saving data from the class back to an Xml file is equally as easy.

NOTE: Feel free to hand edit the generated files (but understand if you regenerate them, your changes will be lost). I generally use the xsd.exe tool first and then hand edit. Xsd.exe will generate any collections using raw arrays (e.g. myField[]) which I don’t like to use because users of the class need to always check for null in order to loop the items. So I hand edit and replace these arrays with generic List<>’s.

No comments:

Post a Comment