将XmlElements反序列化为嵌套的复杂类型

时间:2017-12-20 21:06:06

标签: c# xml deserialization

有没有办法将XmlElements反序列化为嵌套的复杂对象。我正在尝试使用URL,用户名和密码填充ServiceProvider.Properties对象。目前所有值都为null。

public class ServiceProvider 
{
   [XmlElement("ID")]
   public SettingId SettingId { get; set; }

   public Properties Properties { get; set; }    
}

public class Properties
{
    [XmlElement]
    public string Username { get; set; }

   [XmlElement]
   public string URL { get; set; }

   [XmlElement]
   public string Password { get; set; }
}

public class SettingId 
{
    [XmlElement]
    public string Key { get; set; }

    [XmlElement]
    public string Domain { get; set; }

    [XmlElement]
    public string Type { get; set; }
}
<ServiceProviders>
    <ServiceProvider>
      <ID>
          <Key>Key</Key>
          <Domain>Domain</Domain>
          <Type>Type</Type>
      <ID>
      <URL>URL</URL>
      <Username>User</Username>      
      <Password>Password</Password>
  </ServiceProvider>
</ServiceProviders>

1 个答案:

答案 0 :(得分:0)

没有&#39;属性&#39; XML中的标记。而是删除它,只需将该类中的字段添加到ServiceProvider类中。确保您有XMLRoot("ServiceProviders")将此类作为字段

public class ServiceProvider 
{
    [XmlElement("ID")]
    public SettingId SettingId { get; set; }

    [XmlElement]
    public string Username { get; set; }

    [XmlElement]
    public string URL { get; set; }

    [XmlElement]
    public string Password { get; set; }
}