【问题标题】:Deserialize XmlElements to nested complex type将 XmlElements 反序列化为嵌套的复杂类型
【发布时间】:2017-12-20 21:06:05
【问题描述】:

有没有办法将 XmlElements 反序列化为嵌套的复杂对象。我试图让 URL、用户名和密码填充 ServiceProvider.Properties 对象。目前所有的值都是空的。

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>

【问题讨论】:

  • 感谢您的重播,但这就是我现在对其进行编码的方式,并且属性对象中的值为 null。
  • 您的 XML 无效。顺便说一句&lt;/ID&gt;

标签: c# xml deserialization


【解决方案1】:

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

【讨论】:

  • 您的示例是我最初拥有它并且它正在工作的方式。我希望在反序列化期间将这些值转换为 Properties 对象。基本上采用这些元素并将它们映射到复杂的嵌套对象。我认为不编写自定义反序列化代码是不可能的。感谢您的回复
  • @kamce 你为什么要这么做?
  • 这是当前类的定义方式。我只是想将它强制转换为那种格式,而不必添加不同的类,然后映射到现有的类。
猜你喜欢
  • 2017-04-13
  • 2018-03-20
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
相关资源
最近更新 更多