繁体   English   中英

如何将XML反序列化为对象

[英]How to Deserialize XML into object

我正在遵循此代码,但是我无法访问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数据。

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

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

而来自Branch属性的同一件事:

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

您可以使用Visual Studio的“特殊粘贴”功能为xml生成c#代码。

首先,您可以使用一些在线工具,例如:

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不能那么高,我只需要将Age字段从xs:byte更改为xs:int即可:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM