Chris Straw
SHARE:

Generate c# or vb.net class from XML file

Spread the love

XSD is a 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.

For my example, I’m using the?GetBusinessCardCall from the Shoeboxed.com API. ?I am currently writing a c#?interface?to read the data from Shoeboxed. ?I will be posting the entire project soon!

To get started, just go your Visual Studio Command Prompt?(Start -> Visual Studio xxxx-> Visual Studio Tools -> Visual Studio Command Prompt). ?There is not a graphical interface to this tool.

Visual Studio 2010 Command Prompt

***************************************************************************************

note: you will want to change directories to the location of your xml file. ?If you don’t, the files will be generated to the path shown in the command prompt.

to change directories, just use type ?cd “c:\yourpathhere\”

***************************************************************************************

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 yourfilename.xml
VS 2010 XSD tool
Create XSD from XML file using VS 2010 XSD tool

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="GetBusinessCardCallResponse" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="GetBusinessCardCallResponse" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="BusinessCards">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="BusinessCard" minOccurs="0" maxOccurs="unbounded">
                <xs:complexType>
                  <xs:attribute name="id" type="xs:string" />
                  <xs:attribute name="firstName" type="xs:string" />
                  <xs:attribute name="lastName" type="xs:string" />
                  <xs:attribute name="createDate" type="xs:string" />
                  <xs:attribute name="address" type="xs:string" />
                  <xs:attribute name="address2" type="xs:string" />
                  <xs:attribute name="city" type="xs:string" />
                  <xs:attribute name="state" type="xs:string" />
                  <xs:attribute name="zip" type="xs:string" />
                  <xs:attribute name="country" type="xs:string" />
                  <xs:attribute name="email" type="xs:string" />
                  <xs:attribute name="website" type="xs:string" />
                  <xs:attribute name="company" type="xs:string" />
                  <xs:attribute name="position" type="xs:string" />
                  <xs:attribute name="workPhone" type="xs:string" />
                  <xs:attribute name="cellPhone" type="xs:string" />
                  <xs:attribute name="fax" type="xs:string" />
                  <xs:attribute name="frontImgUrl" type="xs:string" />
                  <xs:attribute name="envelopeCode" type="xs:string" />
                  <xs:attribute name="note" type="xs:string" />
                  <xs:attribute name="backImgUrl" type="xs:string" />
                </xs:complexType>
              </xs:element>
            </xs:sequence>
            <xs:attribute name="count" type="xs:string" />
          </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 normally does 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.

xsd yourfilename.xsd /classes

vb.net:

xsd yourfilename.xsd /language:vb /classes

This will then generate a .cs (or .vb) source file that you can add into your project.

VS 2010 XSD tool to generate classes
Create .cs file from XSD file using VS 2010 XSD tool

Here is the code from the .cs file. ?I know that it’s ugly, but it’s a start. I’m going to clean this up and show an example of the entire code in a later post.

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.225
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class GetBusinessCardCallResponse {

    private GetBusinessCardCallResponseBusinessCards[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("BusinessCards", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public GetBusinessCardCallResponseBusinessCards[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class GetBusinessCardCallResponseBusinessCards {

    private GetBusinessCardCallResponseBusinessCardsBusinessCard[] businessCardField;

    private string countField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("BusinessCard", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public GetBusinessCardCallResponseBusinessCardsBusinessCard[] BusinessCard {
        get {
            return this.businessCardField;
        }
        set {
            this.businessCardField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string count {
        get {
            return this.countField;
        }
        set {
            this.countField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class GetBusinessCardCallResponseBusinessCardsBusinessCard {

    private string idField;

    private string firstNameField;

    private string lastNameField;

    private string createDateField;

    private string addressField;

    private string address2Field;

    private string cityField;

    private string stateField;

    private string zipField;

    private string countryField;

    private string emailField;

    private string websiteField;

    private string companyField;

    private string positionField;

    private string workPhoneField;

    private string cellPhoneField;

    private string faxField;

    private string frontImgUrlField;

    private string envelopeCodeField;

    private string noteField;

    private string backImgUrlField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string id {
        get {
            return this.idField;
        }
        set {
            this.idField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string firstName {
        get {
            return this.firstNameField;
        }
        set {
            this.firstNameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string lastName {
        get {
            return this.lastNameField;
        }
        set {
            this.lastNameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string createDate {
        get {
            return this.createDateField;
        }
        set {
            this.createDateField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string address {
        get {
            return this.addressField;
        }
        set {
            this.addressField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string address2 {
        get {
            return this.address2Field;
        }
        set {
            this.address2Field = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string city {
        get {
            return this.cityField;
        }
        set {
            this.cityField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string state {
        get {
            return this.stateField;
        }
        set {
            this.stateField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string zip {
        get {
            return this.zipField;
        }
        set {
            this.zipField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string country {
        get {
            return this.countryField;
        }
        set {
            this.countryField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string email {
        get {
            return this.emailField;
        }
        set {
            this.emailField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string website {
        get {
            return this.websiteField;
        }
        set {
            this.websiteField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string company {
        get {
            return this.companyField;
        }
        set {
            this.companyField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string position {
        get {
            return this.positionField;
        }
        set {
            this.positionField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string workPhone {
        get {
            return this.workPhoneField;
        }
        set {
            this.workPhoneField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string cellPhone {
        get {
            return this.cellPhoneField;
        }
        set {
            this.cellPhoneField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string fax {
        get {
            return this.faxField;
        }
        set {
            this.faxField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string frontImgUrl {
        get {
            return this.frontImgUrlField;
        }
        set {
            this.frontImgUrlField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string envelopeCode {
        get {
            return this.envelopeCodeField;
        }
        set {
            this.envelopeCodeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string note {
        get {
            return this.noteField;
        }
        set {
            this.noteField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string backImgUrl {
        get {
            return this.backImgUrlField;
        }
        set {
            this.backImgUrlField = value;
        }
    }
}

How it works

The details of how this works is a relatively?simple process. ?The classes generated contain properties equal the attributes/elements within the XML file. ?The deserialization process, which built within the .Net framework, will take the xml?representation?of the class and create the instantiated object using the class type you provide (see below for the code).

If you are familiar with webservices, this process works the same as the WSDL.exe in generating a proxy class for the service. ?Actually, the WSDL.exe uses the XSD.exe to generate the classes to represent the SOAP contracts.

Xml Deserialization

To create a object that from the generated classes that’s loaded with the data from the XML file, we need to use the deserialization process within the .Net framework.

            StreamReader str = new StreamReader(@"C:\Shoeboxed\GetBusinessCardResult.xml");

            XmlSerializer xSerializer = new XmlSerializer(typeof(GetBusinessCardCallResponse));

            GetBusinessCardCallResponse bcResponse = (GetBusinessCardCallResponse)xSerializer.Deserialize(str);

            foreach (GetBusinessCardCallResponseBusinessCards result in bcResponse.Items.ToList<GetBusinessCardCallResponseBusinessCards>())
            {
                var businessCards = result.BusinessCard.ToArray<GetBusinessCardCallResponseBusinessCardsBusinessCard>();

                foreach (GetBusinessCardCallResponseBusinessCardsBusinessCard bc in businessCards)
                {
                    Console.Write(bc.firstName);
                    Console.Write(" ");
                    Console.WriteLine(bc.lastName);
                }

                Console.WriteLine();
            }
            str.Close();

            Console.ReadLine();

This code deserializes?the xml file into the classes generated by the XSD tool and interates through the records and writes the name out to the console. ?I will be posting the entire code for the Shoeboxed API later!