Web Design that taps into the haromny and vision of your dreams.

Using XSD Tool to Generate Classes from XML

Generate POCO from XML and XSD

Written By on in C#

649 words, estimated reading time 3 minutes.

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.

Using Visual Studio Series
  1. Getting Started with Visual Studio
  2. Using the Visual Studio Integrated Development Environment
  3. Using the Visual Studio Debugger
  4. XML Documentation in Visual Studio
  5. Using Microsoft .Net Command Line Tools
  6. What is an Assembly in Microsoft .Net?
  7. Creating and Using a .NET Assembly in C#
  8. Creating and Implementing Satellite Assemblies
  9. Creating Strong Named Assemblies in Microsoft .Net
  10. Visual Studio Task List
  11. Resources and Localisation in C# Projects
  12. Localising Microsoft .Net Applications with C#
  13. Using Resource Files in C# Applications
  14. Using XSD Tool to Generate Classes from XML
  15. 10 Visual Studio Tools You May Not Know About

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 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

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 an 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 shown below.

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();
    }
  }
}

Last updated on: Thursday 22nd June 2017

 

Comments
Wad

Wad

That did the trick. Thanks for the article.

Reply to Wad
muzi

muzi

thanks mate, this is what i was looking for.

Reply to muzi
RZA

RZA

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"

Reply to RZA
Br.Bill

Br.Bill

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.

Reply to Br.Bill
Rahul

Rahul

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.

Reply to Rahul

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me