如何将XML反序列化为对象

时间:2017-03-27 11:43:22

标签: c# .net xml deserialization xml-deserialization

我正在关注此代码,但我无法访问xml数据。

我想在C#中反序列化以下XML和对象类:

XML文件

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

我有

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

我的代码

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

    }
}

我想将所有xml数据存储到Object中。

我试过但无法访问xml数据。

2 个答案:

答案 0 :(得分:1)

这里你不需要XmlArray属性,你只需要使用XmlElementAttribute:

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

与Branch属性相同:

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

您可以使用visual studio的“Paste special”功能为您的xml生成c#代码。

答案 1 :(得分:0)

首先,您可以使用以下在线工具:

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

然后你会得到一个XSD,您可以自定义所有类型:

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

更改后更新:

这里我只需将Age字段从xs:byte更改为xs:int,即使Age不能那么高:

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

然后,您可以打开开发人员提示并使用Microsoft的XSD.EXE工具,然后获得C#类:

xsd.exe /c Test.xsd

结果如下:

//------------------------------------------------------------------------------
// <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;
        }
    }
}