Auto Generating C# wrapper for parsing XML files

While working with xmls, many a times I see starting the xml and seeing the insanely mundane but manual task of writing parser classes in C#. Then xsd found me.

if you are like me, you will benefit a bit from this post.

here is a step by step to start with an xml and end up with a full .cs file to parse the input xml.

 

lets say you have an input xml

  1. <Master>
  2. <Customer>
  3. <Name
    Gender=Male>Bill</Name>
  4. <Age>34</Age>
  5. </Customer>
  6. </Master>

     

Step 1

Load this xml file in visual studio (2008 or 2010). You should see a Menu “XML”, and under which you should see a “Create Schema” Menu Item

On clicking “Create Schema”, an xsd file will be generated :

Save this xsd file (say c:\temp\input.xsd)

It is time now to create the cs file.

Search for “visual studio command prompt” in Start search bar.

Open the command prompt. Type in

C:\temp>xsd /c /l:cs /n:MyNamespace Input.xsd

/c represents “generate classes for this schema”

/l represents the language in which the classes are to be generated in. You can use CS, VB, JS

/n represents the namespace

And input.xsd is the generated schema file from above.

 

The output of this command is a cs file in the same folder c:\temp\input.cs

Here are the contents of this file:

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: