user7773677
user7773677

Reputation:

How to Deserialize XML into object

I am having following this code but i can't access xml data.

I would like to deserialize the following XML to and object class in C#:

XML File is :

<EmployeeCollection>
  <EmployeeDetail>
    <Employee ID ="EMP-01"> 
        <Name>ABC</Name>
        <MobileNumber>9876543210</MobileNumber>
        <Age>20</Age>
        <Gender>Male</Gender>
        <MartialStatus>Single</MartialStatus>
        <DOB>1997-01-12</DOB>
        <Branch Name="XYZ">
            <CountryCode>IND</CountryCode>
            <EstablishmentDate>2013-01-15</EstablishmentDate>
        </Branch>
    </Employee>
    <Employee ID ="EMP-02"> 
        <Name>DEF</Name>
        <MobileNumber>9685741236</MobileNumber>
        <Age>19</Age>
        <Gender>Male</Gender>
        <MartialStatus>Single</MartialStatus>
        <DOB>19998-12-21</DOB>
        <Branch Name="PQR">
            <CountryCode>US</CountryCode>
            <EstablishmentDate>2011-01-23</EstablishmentDate>
        </Branch>
    </Employee>
  </EmployeeDetail>
</EmployeeCollection>

I have this:

public class Employee
{
    [XmlAttribute("ID")]
    public string ID                { get; set; }

    [XmlElement("Name")]
    public string Name              { get; set; }

    [XmlElement("MobileNumber")]
    public long MobileNumber        { get; set; }

    [XmlElement("Age")]
    public int Age                  { get; set; }

    [XmlElement("Gender")]
    public string Gender            { get; set; }

    [XmlElement("MartialStatus")]
    public string MartialStatus     { get; set; }

    [XmlElement("DOB")]
    public DateTime DOB                 { get; set; }

    [XmlArray("Branch")]
    public BranchDetail[] Branch    { get; set; }
}

public class BranchDetail
{
    [XmlAttribute("Name")]
    public string BranchName        { get; set; }

    [XmlElement("CountryCode")]
    public string CountryCode       { get; set; }

    [XmlElement("EstablishmentDate")]
    public DateTime EstablishmentDate { get; set; }
}

[XmlRoot("EmployeeDetail")]
public class EmployeeCollection
{
    [XmlArray("Employee")]
    public Employee[] Employee      { get; set; }
}

My Code is :

public class EmployeeSerializer
{
    public void Deserialize()
    {
        EmployeeCollection Employees = null; 

        XmlSerializer serializer = new XmlSerializer(typeof(EmployeeCollection));

        StreamReader reader = new StreamReader(employee.xml);

        Employees = (EmployeeCollection)serializer.Deserialize(reader);

        reader.Close();

    }
}

I want to store all xml data into Object.

I tried but can not access xml data.

Upvotes: 0

Views: 7263

Answers (2)

Nicolas Vannier
Nicolas Vannier

Reputation: 108

First, you can use some online tool like this one :

http://www.freeformatter.com/xsd-generator.html

Then you get an XSD where you can customize all types :

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="EmployeeDetail">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="Employee" maxOccurs="unbounded" minOccurs="0">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element type="xs:string" name="Name"/>
                        <xs:element type="xs:long" name="MobileNumber"/>
                        <xs:element type="xs:byte" name="Age"/>
                        <xs:element type="xs:string" name="Gender"/>
                        <xs:element type="xs:string" name="MartialStatus"/>
                        <xs:element type="xs:date" name="DOB"/>
                        <xs:element name="Branch">
                            <xs:complexType>
                                <xs:sequence>
                                    <xs:element type="xs:string" name="CountryCode"/>
                                    <xs:element type="xs:date" name="EstablishmentDate"/>
                                </xs:sequence>
                                <xs:attribute type="xs:string" name="Name" use="optional"/>
                            </xs:complexType>
                        </xs:element>
                    </xs:sequence>
                    <xs:attribute type="xs:string" name="ID" use="optional"/>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>

UPDATED following your changes :

Here I only have to change the Age field from xs:byte to xs:int, even though an Age cannot be that high :

                            <xs:element type="xs:int" name="Age"/>

Then you can open a Developer Prompt and use the XSD.EXE tool from Microsoft, and you get a C# class :

xsd.exe /c Test.xsd

Here is the result :

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     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.17929.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[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 EmployeeDetail {

    private EmployeeDetailEmployee[] employeeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Employee")]
    public EmployeeDetailEmployee[] Employee {
        get {
            return this.employeeField;
        }
        set {
            this.employeeField = value;
        }
    }
}

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

    private string nameField;

    private long mobileNumberField;

    private int ageField;

    private string genderField;

    private string martialStatusField;

    private System.DateTime dOBField;

    private EmployeeDetailEmployeeBranch branchField;

    private string idField;

    /// <remarks/>
    public string Name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }

    /// <remarks/>
    public long MobileNumber {
        get {
            return this.mobileNumberField;
        }
        set {
            this.mobileNumberField = value;
        }
    }

    /// <remarks/>
    public int Age {
        get {
            return this.ageField;
        }
        set {
            this.ageField = value;
        }
    }

    /// <remarks/>
    public string Gender {
        get {
            return this.genderField;
        }
        set {
            this.genderField = value;
        }
    }

    /// <remarks/>
    public string MartialStatus {
        get {
            return this.martialStatusField;
        }
        set {
            this.martialStatusField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType="date")]
    public System.DateTime DOB {
        get {
            return this.dOBField;
        }
        set {
            this.dOBField = value;
        }
    }

    /// <remarks/>
    public EmployeeDetailEmployeeBranch Branch {
        get {
            return this.branchField;
        }
        set {
            this.branchField = value;
        }
    }

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

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

    private string countryCodeField;

    private System.DateTime establishmentDateField;

    private string nameField;

    /// <remarks/>
    public string CountryCode {
        get {
            return this.countryCodeField;
        }
        set {
            this.countryCodeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(DataType="date")]
    public System.DateTime EstablishmentDate {
        get {
            return this.establishmentDateField;
        }
        set {
            this.establishmentDateField = value;
        }
    }

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

Upvotes: 1

Maksim Simkin
Maksim Simkin

Reputation: 9679

You don't need XmlArray Attributes here, you cuold just use XmlElementAttribute:

[XmlRoot("EmployeeDetail")]
public class EmployeeCollection
{
    [XmlElementAttribute("Employee")]   
    public Employee[] Employee { get; set; }
}

And the same thing from Branch property:

[XmlElementAttribute("Branch")]
public BranchDetail[] Branch { get; set; }

You could use function "Paste special" of visual studio to generate c# code for your xml.

Upvotes: 2

Related Questions