【问题标题】:How to Deserialize XML into object如何将 XML 反序列化为对象
【发布时间】:2017-08-20 02:31:35
【问题描述】:

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

我想将以下 XML 反序列化为 C# 中的对象类:

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 数据。

【问题讨论】:

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


    【解决方案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# 代码。

    【讨论】:

      【解决方案2】:

      首先,你可以使用一些像这样的在线工具:

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

      然后你可以打开一个开发者提示并使用微软的 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;
              }
          }
      }
      

      【讨论】:

      • @Roland Shaw 这个问题的第一个版本不是这种情况。对该问题进行了多次编辑,这个答案是一个通用的“如何”以避免手动映射到对象。不是投反对票的理由:(
      • 问题的初始版本确实为 XML 序列化标记了类,即使那样,您的回答也没有解决 如何 序列化/反序列化数据
      猜你喜欢
      • 2018-10-11
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 2014-11-30
      相关资源
      最近更新 更多