all Technical posts

Auto-generate class-file from an XSD

Autogenerate an class-file from an XSD every time you build your Visual Studio project with svcutil.

Sometimes when you create an XSD, you need to deserialize it to a class file so you can use it in your .NET code. You can easily do that with SVCUTIL.

This can be automated in your Visual Studio project-file so that every time that project is build, svcutil regenerates the class-file.

For this example, I’ve created a simple Class Library and added an XSD-file named Person.xsd. It’s pretty simple and looks like this:

 Person

Now to add the auto-generate functionality, you’ll need to open the project-file (in my case .csproj-file) in a text-editor like notepad++.

First of all, you’ll need to add this property group below in order to use svcutil. Add it at the bottom or your file, just before the target-nodes.

<PropertyGroup>
<WIN_SDK_PATH>$(Registry:HKEY_LOCAL_MACHINESOFTWAREMicrosoftMicrosoft SDKsWindows@CurrentInstallFolder)</WIN_SDK_PATH>
<WIN_SDK_BIN_PATH>$(WIN_SDK_PATH)bin</WIN_SDK_BIN_PATH>
<SVCUTIL>”$(WIN_SDK_BIN_PATH)svcutil.exe”</SVCUTIL>
</PropertyGroup>

Now right below the just added PropertyGroup, add this piece of xml below. This is kind of like a function that we will call later. It contains the svcutil-command that will generate class Person.xsd.cs. For more info about svcutil, take a look here.

<Target Name=”XSDDeserialization”>
<Exec Outputs=”Person.xsd.cs” Command=”$(SVCUTIL) /dconly /serializer:DataContractSerializer /serializable “/n:http://Codit.Demo.XsdSampleApplication,Codit.Demo.XsdSampleApplication” /language:C# “/out:Person.xsd.cs” “*.xsd” ” />
</Target>

Then we need to uncomment or add this Target-node. This will call the svcutil-command on the BeforeBuild-event. 

<Target Name=”BeforeBuild” DependsOnTargets=”XSDDeserialization”>
</Target>

Now open the project in Visual Studio and build the project. If you look in the folder of that project, you’ll see that a class (in my case Person.xsd.cs) is generated. Add it to the project so that it can be used. You’ll need to add the reference System.Runtime.Serialization in order to get it to build. From now on, every time you’ll build the class will be regenerated.  

One downside is, when your code is in TFS, you’ll need to check out the class-file. If not, your project won’t be able to build, because your class-file will be read-only and can’t be overwritten.

Reference: http://stevehorsfield.wordpress.com/2009/06/17/automate-xsd-code-generation-in-visual-studio/

Subscribe to our RSS feed

Hi there,
how can we help?

Got a project in mind?

Connect with us

Let's talk

Let's talk

Thanks, we'll be in touch soon!

Call us

Thanks, we've sent the link to your inbox

Invalid email address

Submit

Your download should start shortly!

Stay in Touch - Subscribe to Our Newsletter

Keep up to date with industry trends, events and the latest customer stories

Invalid email address

Submit

Great you’re on the list!