Using XSD Tool to Generate Classes from XML

XSD tool is a simple tool that can be used to generate a C# class from a given XML document and we can then load data into that class in C#.

By Tim Trott | C# ASP.Net MVC | November 20, 2008

XSD is a simple tool that can be used to generate a C# class from a given XML document. This class can then be used to deserialize and process the XML within your code.

To get started you will need an XML file, in this example, I will again use the cd catalogue XML from W3 Schools .

You will need to run the XSD.EXE tool from the Visual Studio Command Prompt (Start -> Visual Studio 2005 -> Visual Studio Tools -> Visual Studio Command Prompt) as there is no graphical front end for the tool.

The first step is to generate an XML schema from the file (skip this if you already have one).

On the command prompt type:

xsd cd_catalog.xml

This will generate a schema for the file, which we can use to generate our classes.

You should now have something like this on the screen:

C:\Sharper>xsd cd_catalog.xml
Microsoft (R) XML Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\Sharpercd_catalog.xsd'.
C:\Sharper>

The XSD schema will look similar to the XML file, but it will not contain any data. It is used to define the structure and the type of data that the XML will hold.

xml
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="CATALOG" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="CATALOG" msdata:IsDataSet="true" msdata:Locale="en-US">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="CD">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="TITLE" type="xs:string" minOccurs="0" />
              <xs:element name="ARTIST" type="xs:string" minOccurs="0" />
              <xs:element name="COUNTRY" type="xs:string" minOccurs="0" />
              <xs:element name="COMPANY" type="xs:string" minOccurs="0" />
              <xs:element name="PRICE" type="xs:string" minOccurs="0" />
              <xs:element name="YEAR" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

Next, we can use the XSD file to generate our class(es). The generated XSD can (and often do) contain multiple classes, so it would be better to use /classes switch which tells xsd.exe to generate all the code. The default language is C#, however, if you wish to have the code generated in VB.Net simply add the switch /language:vb.

C:\Sharper>xsd cd_catalog.xsd /classes
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\Sharpercd_cataloge.cs'.

This will then generate a .cs source file that you can incorporate into your project(s).

Xml Deserialization

To use the original XML data in our project, all we need to do is deserialize the XML file using the class we just generated. By creating an XML schema and adding it to a project, Visual Studio will create strongly typed DataSet for you as well. Anyway, the deserialization code is shown below.

C#
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      StreamReader str = new StreamReader("cd_catalog.xml");
      XmlSerializer xSerializer = new XmlSerializer(typeof(CATALOG));
      
      CATALOG myCdCatalogue = (CATALOG)xSerializer.Deserialize(str);

      foreach (CATALOG.CDRow cd in myCdCatalogue.CD)
      {
        Console.WriteLine(cd.TITLE);
        Console.WriteLine(cd.ARTIST);
        Console.WriteLine(cd.COUNTRY);
        Console.WriteLine(cd.COMPANY);
        Console.WriteLine(cd.PRICE);
        Console.WriteLine(cd.YEAR);
        Console.WriteLine();
      }
      str.Close();
    }
  }
}
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 6 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. MM

    On Saturday 5th of October 2019, Mads Munk said

    Nice example it was helpful but is there a place where I can download a solution for this example or the xml data file. I'm still having some trouble with visual studio and some other xml stuff, so a working example would be very nice ?

  2. WA

    On Thursday 16th of February 2012, Wad said

    That did the trick. Thanks for the article.

  3. MU

    On Wednesday 7th of September 2011, muzi said

    thanks mate, this is what i was looking for.

  4. RZ

    On Sunday 27th of February 2011, RZA said

    You need to add the namespace of your project to the xsd command via /n:"my.name.space"

    Then you will see the classes

    f.e.
    xsd cd_catalog.xsd /classes /n:"this.is.my.namespace"

  5. BB

    On Tuesday 12th of October 2010, Br.Bill said

    Regarding the following section of your article:

    "This will then generate a .cs source file that you can incorporate into your project(s).

    Xml Deserialization

    In order to use the original XML data in our project, all we need to do is deserialize the XML file using the class we just generated. By creating a XML schema and adding it to a project, Visual Studio will create a strongly typed DataSet for you as well. Anyway the deserialization code is show below."

    You're jumping over a big gap here. Could you please explain this magic? How are the .cs and .xsd files "incorporated" ? I add them to my VS project but I see no special anything that makes them available to my main .cs program. Or yours.

    1. RA

      On Thursday 28th of April 2011, Rahul replied

      One way would be to put the generated classes in a namespace and put a using namespace statement in the file where you want to use these classes. The Class should be available now.