Tuesday, December 22, 2009

CodeGenerator From XML Schemas using Visual Studion XSD.exe

XSD.exe is a nice tool for .NET Code-Generation from an existing xml Schema. It's very similar like its java counterpart (JAXB- XJC)


Syntax:

Visual Studio 9.0\VC>xsd /c /out:c:\aneesh\classes c:\Aneesh\dataTypes.xsd

/c stands for generating classes
/out specifies the output directory
/namespace can give a specific namespace for the generated class


A bit complex situation, with multiple schema's

Scenario:

You have an XSD, objectrSchema.xsd and you have another XSD dataTypes.xsd. Some of the DataTypes in the dataTypes.xsd are used in the objectSchema.xsd. In this situation if you run the above command, it will give you a straight error:

Warning: Schema could not be validated. Class generation may fail or may produce incorrect results.
Error: Error generating classes for schema 'c:\ Aneesh\objectSchema.xsd '.

We can overcome this situation with a few tweaks. Thought I searched google but didn’t yield any satisfactory results. These are thing steps I did to make it work.

Step 1:

Import the dataTypes.xsd into the objectrSchema.xsd using the More details of XD IMport can be found here.

Note that the “namespace=http://www.aneesh.com/datatypes “should be the same as the one defined in dataTypes.xsd

Step 2:

Finally hit the command:

Visual Studio 9.0\VC>xsd /c /out:c:\aneesh\classes c:\Aneesh\dataTypes.xsd c:\Aneesh\objectSchema.xsd

Here you go. Your code is generated. Happy Hacking!

More Reading