Blog from Saravanan Arumugam

Let us talk about Technologies

How to Generate Classes from XSD file


There are many instances where we may be in need of making class file (.cs, .vb, etc) out of xml schema files (XSD) or vice versa.

Here is an example scenario. In the traditional service oriented non-.Net platforms the service is defined in WSDL and the Data contracts are usually provided in the form of XSD.

When attempting to use the service in .net application, we may be in need of making classes out of the xsd files.

One of the .Net framework provided tools “XML Schema Definition Tool (xsd.exe)” helps us convert XSD into Classes and vice versa.

In this blog, I am going to explain how to

1. Create to create Classes from XSD file,

2. Create XSD from .Net classes,

3. Create XSD from XML files.

 

Creating Classes from XSD

Step 1: Use the .net command prompt and move to the directory where the xsd file is available.

Example:

cd c:\MyProjects\BookManager\Book

 

Step 2: Use the xsd.exe command with the following swithches

/classes or /c – Creates Classes out of XSD

/language: <language> or /l: <language> – programming language.

<language> can be vb, cs, js, vjs, cpp

/namespace: <namespace> or /n: <namespace> – Specifies the namespace of the out coming classes.

Example:

xsd /c /l:cs /n:Books Books.xsd

 

Here is the structure of the xsd I tried and the cs file output.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema&quot;
            targetNamespace="urn:books"
            xmlns:bks="urn:books">
  <xsd:element name="books" type="bks:BooksForm"/>
  <xsd:complexType name="BooksForm">
    <xsd:sequence>
      <xsd:element name="book"
                  type="bks:BookForm"
                  minOccurs="0"
                  maxOccurs="unbounded"/>
      </xsd:sequence>
  </xsd:complexType>
  <xsd:complexType name="BookForm">
    <xsd:sequence>
      <xsd:element name="author"   type="xsd:string"/>
      <xsd:element name="title"    type="xsd:string"/>
      <xsd:element name="genre"    type="xsd:string"/>
      <xsd:element name="price"    type="xsd:float" />
      <xsd:element name="pub_date" type="xsd:date" />
      <xsd:element name="review"   type="xsd:string"/>
    </xsd:sequence>
    <xsd:attribute name="id"   type="xsd:string"/>
  </xsd:complexType>
</xsd:schema>

//——————————————————————————
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//——————————————————————————
//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//
namespace Books {
    using System.Xml.Serialization;
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:books")]
    [System.Xml.Serialization.XmlRootAttribute("books", Namespace="urn:books", IsNullable=false)]
    public partial class BooksForm {
        private BookForm[] bookField;
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("book", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public BookForm[] book {
            get {
                return this.bookField;
            }
            set {
                this.bookField = value;
            }
        }
    }
    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:books")]
    public partial class BookForm {
        private string authorField;
        private string titleField;
        private string genreField;
        private float priceField;
        private System.DateTime pub_dateField;
        private string reviewField;
        private string idField;
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string author {
            get {
                return this.authorField;
            }
            set {
                this.authorField = value;
            }
        }
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string title {
            get {
                return this.titleField;
            }
            set {
                this.titleField = value;
            }
        }
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string genre {
            get {
                return this.genreField;
            }
            set {
                this.genreField = value;
            }
        }
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public float price {
            get {
                return this.priceField;
            }
            set {
                this.priceField = value;
            }
        }
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, DataType="date")]
        public System.DateTime pub_date {
            get {
                return this.pub_dateField;
            }
            set {
                this.pub_dateField = value;
            }
        }
        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string review {
            get {
                return this.reviewField;
            }
            set {
                this.reviewField = value;
            }
        }
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string id {
            get {
                return this.idField;
            }
            set {
                this.idField = value;
            }
        }
    }
}

Creating XSD out of .Net classes

XSD can be created from .Net classes.

Step 1: Use the .net command prompt and move to the directory where the dll file is available.

Note: Direct conversion from .cs file or .vb file was the one I was looking for. But I couldn’t find it. Moreover using .dll makes more sense than using .cs file, so that the XSD command would be language independent.

Example:

cd c:\MyProjects\BookManager\Book

 

Step 2: Use the xsd classfile.dll command to generate xsd schema out of it.

xsd Task.Entities.dll

Usually the xsd generated would be with the name schema0.xsd.

 

Here is the class file and the outcome of XSD.exe

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
namespace Tasks.Entities
{
    [DataContract(Namespace = "http://8fingergenie.com&quot;)]
    public enum TaskState : int
    {
        [DataMember()]
        Active = 0,
        [DataMember()]
        CompletedByDueDate = 1,
        [DataMember()]
        CompletedPastDueDate = 2,
        [DataMember()]
        Overdue = 3
    }
    [DataContract(Namespace = "http://8fingergenie.com&quot;)]
    public class FaultInfo
    {
        [DataMember(IsRequired = true, Order = 0)]
        public string Reason;
    }
    [DataContract(Namespace = "http://8fingergenie.com&quot;)]
    public class Task
    {
        [DataMember(IsRequired = false)]
        public int TaskNumber;
        [DataMember(IsRequired = true)]
        public string Description;
        [DataMember(IsRequired = false)]
        public TaskState TaskState;
        [DataMember(IsRequired = false)]
        public string AssignedTo;
        [DataMember(IsRequired = false)]
        public string CreatedBy;
        [DataMember(IsRequired = false)]
        public DateTime CreatedDate;
        [DataMember(IsRequired = false)]
        public DateTime LastModifiedDate;
        [DataMember(IsRequired = false)]
        public DateTime DueDate;
        public override string ToString()
        {
            return String.Format("Task Name: {0} (Task Number: {1}) is assigned to {2}", Description, TaskNumber, CreatedBy);
        }
    }
    [DataContract(Namespace = "http://8fingergenie.com&quot;)]
    public class TaskAcknowledgement
    {
        [DataMember(IsRequired = false)]
        public int TaskNumber;
        [DataMember(IsRequired = false)]
        public TaskState TaskState;
        [DataMember(IsRequired = false)]
        public string Comment;
    }
}

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt;
  <xs:element name="TaskState" type="TaskState" />
  <xs:simpleType name="TaskState">
    <xs:restriction base="xs:string">
      <xs:enumeration value="Active" />
      <xs:enumeration value="CompletedByDueDate" />
      <xs:enumeration value="CompletedPastDueDate" />
      <xs:enumeration value="Overdue" />
    </xs:restriction>
  </xs:simpleType>
  <xs:element name="FaultInfo" nillable="true" type="FaultInfo" />
  <xs:complexType name="FaultInfo">
    <xs:sequence>
      <xs:element minOccurs="0" maxOccurs="1" name="Reason" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
  <xs:element name="Task" nillable="true" type="Task" />
  <xs:complexType name="Task">
    <xs:sequence>
      <xs:element minOccurs="1" maxOccurs="1" name="TaskNumber" type="xs:int" />
      <xs:element minOccurs="0" maxOccurs="1" name="Description" type="xs:string" />
      <xs:element minOccurs="1" maxOccurs="1" name="TaskState" type="TaskState" />
      <xs:element minOccurs="0" maxOccurs="1" name="AssignedTo" type="xs:string" />
      <xs:element minOccurs="0" maxOccurs="1" name="CreatedBy" type="xs:string" />
      <xs:element minOccurs="1" maxOccurs="1" name="CreatedDate" type="xs:dateTime" />
      <xs:element minOccurs="1" maxOccurs="1" name="LastModifiedDate" type="xs:dateTime" />
      <xs:element minOccurs="1" maxOccurs="1" name="DueDate" type="xs:dateTime" />
    </xs:sequence>
  </xs:complexType>
  <xs:element name="TaskAcknowledgement" nillable="true" type="TaskAcknowledgement" />
  <xs:complexType name="TaskAcknowledgement">
    <xs:sequence>
      <xs:element minOccurs="1" maxOccurs="1" name="TaskNumber" type="xs:int" />
      <xs:element minOccurs="1" maxOccurs="1" name="TaskState" type="TaskState" />
      <xs:element minOccurs="0" maxOccurs="1" name="Comment" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

Creating XSD out of XML

Creating XSD out of Xml doesn’t involve any special switches.

Use the following command to create XSD.

xsd xmlfile.xml

Example:

xsd XMLBooks.xml

 

Here is the XML file and the resulting XSD.

<?xml version="1.0"?>
<x:books xmlns:x="urn:books">
   <book id="bk001">
      <author>Writer</author>
      <title>The First Book</title>
      <genre>Fiction</genre>
      <price>44.95</price>
      <pub_date>2000-10-01</pub_date>
      <review>An amazing story of nothing.</review>
   </book>

   <book id="bk002">
      <author>Poet</author>
      <title>The Poet’s First Poem</title>
      <genre>Poem</genre>
      <price>24.95</price>
      <review>Least poetic poems.</review>
   </book>
</x:books>

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="books" targetNamespace="urn:books" xmlns:mstns="urn:books" xmlns="urn:books" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified">
  <xs:element name="books" msdata:IsDataSet="true" msdata:UseCurrentLocale="true" msdata:Prefix="x">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="book" form="unqualified">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="author" form="unqualified" type="xs:string" minOccurs="0" msdata:Ordinal="0" />
              <xs:element name="title" form="unqualified" type="xs:string" minOccurs="0" msdata:Ordinal="1" />
              <xs:element name="genre" form="unqualified" type="xs:string" minOccurs="0" msdata:Ordinal="2" />
              <xs:element name="price" form="unqualified" type="xs:string" minOccurs="0" msdata:Ordinal="3" />
              <xs:element name="pub_date" form="unqualified" type="xs:string" minOccurs="0" msdata:Ordinal="4" />
              <xs:element name="review" form="unqualified" type="xs:string" minOccurs="0" msdata:Ordinal="5" />
            </xs:sequence>
            <xs:attribute name="id" form="unqualified" type="xs:string" />
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

Advertisements

2 responses to “How to Generate Classes from XSD file

  1. selvaraj.K December 16, 2012 at 8:42 am

    Hi friend i got a idea about generating other files like .cs, .dll from XML schema. It is very useful one thank you. But i need to generate .cs file from xsd file “Automatically”. we change anything in schema file it will affect and change in .cs file . will
    you able to help me………..

    • Anthony March 26, 2015 at 12:33 pm

      Trying using T4 Templates

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: