简体   繁体   中英

How to deserialize nested XML file into object in C#

I met a very complicated XML structure, I think it's like nested 2D array. But my definition seems not working. I have an Xml structure like below

<Rate>
<GROUP>
    <GROUPNAME>Company</GROUPNAME>
    <COUNTY>Dawson</COUNTY>
</GROUP>
<EMPLOYEES>
    <MEMBERS>
        <MEMBER>
            <SEQUENCENUM>1</SEQUENCENUM>
            <GENDER>M</GENDER>
            <RELATIONSHIP>Father</RELATIONSHIP>
        </MEMBER>
        <MEMBER>
            <SEQUENCENUM>2</SEQUENCENUM>
            <GENDER>F</GENDER>
            <RELATIONSHIP>Mother</RELATIONSHIP>
        </MEMBER>
    </MEMBERS>
    <MEMBERS>
        <MEMBER>
            <SEQUENCENUM>1</SEQUENCENUM>
            <GENDER>M</GENDER>
            <RELATIONSHIP>Father</RELATIONSHIP>
        </MEMBER>
        <MEMBER>
            <SEQUENCENUM>2</SEQUENCENUM>
            <GENDER>Y</GENDER>
            <RELATIONSHIP>Mother</RELATIONSHIP>
        </MEMBER>
    </MEMBERS>
</EMPLOYEES>

And I defined three classes for this structure

[XmlRoot("Rate")]
public class Rate
{
  [XmlElement("GROUP")]
  public GroupInfo Group{get; set;}

  [XmlArray("EMPLOYEES")]
  [XmlArrayItem("MEMBERS", typeof(Members))]
  public List<Members> Employees{get; set;}
}

And this one

[XmlRoot("EMPLOYEES")]
public class Members
{
   [XmlArray("MEMBERS")]
   [XmlArrayItem("MEMBER", typeof(MemberInfo))]
   public List<MemberInfo> Members{get; set;}
}

And this one:

[XmlRoot("Member")]
public class MemberInfo
{
    public string SequenceNum{get; set;}
    
    [XmlElement("GENDER")]
    public string Gender{get; set;}
    
    [XmlElement("RELATIONSHIP")]
    public string Relationship{get; set}
}

Do you guys have any great idea for this? For this nested array?

Add NestingLevel = 1 to your XmlArrayItem attribute.

This class will deserialize your XML.

[Serializable]
[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "", IsNullable = false)]
public class Rate
{
    [XmlElement("GROUP")]
    public Group Group { get; set; }

    [XmlArrayItem("MEMBERS", IsNullable = false)]
    [XmlArrayItem("MEMBER", IsNullable = false, NestingLevel = 1)]
    public Member[][] EMPLOYEES { get; set; }
}

[XmlType(AnonymousType = true)]
public class Group
{
    [XmlElement("GROUPNAME")]
    public string Name { get; set; }

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

[XmlType(AnonymousType = true)]
public class Member
{
    [XmlElement("SEQUENCENUM")]
    public byte Sequencenum { get; set; }

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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