2017-03-27 1 views
0

Je suis en train de suivre ce code, mais je ne peux pas accéder aux données XML.Comment désérialiser XML en objet

Je voudrais désérialiser le XML suivante et classe d'objets en C#:

fichier XML est:

<EmployeeCollection> 
    <EmployeeDetail> 
    <Employee ID ="EMP-01"> 
     <Name>ABC</Name> 
     <MobileNumber></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> 

Je cette:

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

Mon code est:

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

    } 
} 

Je souhaite stocker toutes les données xml dans Object.

J'ai essayé mais je ne peux pas accéder aux données xml.

Répondre

1

Vous n'avez pas besoin XmlArray Attributs ici, vous cuold il suffit d'utiliser XmlElementAttribute:

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

Et la même chose de la propriété de la Direction:

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

Vous pouvez utiliser la fonction "Collage spécial" de Visual Studio pour générer du code C# pour votre xml.

0

D'abord, vous pouvez utiliser un outil en ligne comme celui-ci:

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

Ensuite, vous obtenez un XSD où vous pouvez personnaliser tous les 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> 

MISE À JOUR suivantes vos changements:

Ici seulement à changer le champ Âge de xs: octet xs: int, même si un âge ne peut pas être aussi élevé:

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

Ensuite, vous pouvez ouvrir une invite de développeur et d'utiliser l'outil XSD.exe de Microsoft, et vous obtenir une classe C#:

xsd.exe /c Test.xsd 

Voici le résultat:

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

Anil semble déjà avoir gotton loin –

+0

@Roland Shaw ce ne fut pas le cas dans la première version de cette question. Il y a eu plusieurs modifications à la question, et cette réponse est un "comment" générique pour éviter de faire le mappage pour objecter manuellement. Pas une raison pour downvoting :( –

+0

La version initiale de la question avait des classes balisées pour la sérialisation XML, et même alors, vous répondez ne répond pas * comment * sérialiser/désérialiser les données –