将XML反序列化为对象

时间:2014-10-21 09:41:04

标签: c# xml serialization

我有以下需要反序列化的XML:

<?xml version="1.0" encoding="UTF-8" ?>
<event code="2wuj0ticofhzt" self="/events/2wuj0ticofhzt" revision="1260234836">
  <name>Test Event 2013</name>
  <partner-settings>
    <partner-setting>
      <registration-type code="1yfopbwhk" link="/registration-types/1yfopbwhk" />
        <personnel code="3eclag1dsrjfi">
          <free-badges>unlimited</free-badges>
        </personnel>
        <personnel code="0nxgc6mfec8yh">
          <free-badges>3</free-badges>
       </personnel>
     </partner-setting>
     <partner-setting>
       <registration-type code="1ygg67prw" link="/registration-types/1ygg67prw" />
     </partner-setting>
   </partner-settings>
</event>

以下是我创建的课程。 (我只需要反序列化我的课程中的字段。):

[XmlRoot("event")]
public class Event
{
    [XmlAttribute("code")]
    public string Code { get; set; }

    [XmlAttribute("name")]
    public string EventName { get; set; }

    [XmlArray("partner-settings")]
    public List<PartnerSetting> PartnerSettings { get; set; }
}

[XmlType("partner-setting")]
public class PartnerSetting
{
    [XmlElement("registration-type")]
    public RegistrationType RegistrationType { get; set; }

    [XmlArray("personnel")]
    public List<Personnel> Personnel { get; set; }
}

[XmlRoot("registration-type")]
public class RegistrationType
{
    [XmlAttribute("code")]
    public string Code { get; set; }

    [XmlAttribute("name")]
    public string RegistrationTypeName { get; set; }

    [XmlElement("type")]
    public string Type { get; set; }
}

[XmlType("personnel")]
public class Personnel
{
    [XmlAttribute("code")]
    public string Code { get; set; }

    [XmlElement("free-badges")]
    public int FreeBadges { get; set; }
}

当我当前反序列化上述XML时,除了Personnel对象之外,当我希望看到0时,2返回{{1}}。

当我尝试将人员列表(即XMLArray属性,返回List)返回到合作伙伴设置列表时,我没有做任何不同的事情但由于某种原因它不会反序列化。

1 个答案:

答案 0 :(得分:1)

您需要将属性更改为XmlElement,以强制将列表中的每个元素呈现为单个XML元素:

[XmlElement("personnel")]
public List<Personnel> Personnel { get; set; }