从XML填充对象

时间:2019-03-29 09:06:18

标签: c# json xml dto populate

我有一个这样的现有对象:

Account account = new Account
{
    Email = "james@example.com",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    Roles = new List<string>
    {
        "User",
        "Admin"
    }
};

用于从JSON字符串更新某些属性,例如

string json = @"{
  'Active': false,
  'Roles': [
    'Expired'
  ]
}";

我使用newtonsoft的方法:

JsonConvert.PopulateObject(json, account);

如何从XML字符串执行相同操作?

<Account>
    <Active>false</Active>    
</Account>

谢谢

1 个答案:

答案 0 :(得分:0)

XmlSerializer API没有内置的“合并”功能,但是:它确实支持*Specified模式-含义:如果您具有:

public string Email { get; set; }
[XmlIgnore]
public bool EmailSpecified { get; set; }

然后EmailSpecified a:控制Email是否被序列化,以及b:从有效值反序列化时,将true的值分配给{em> 。因此:您可以执行以下操作:

public class Account
{
    public string Email { get; set; }
    [XmlIgnore]
    public bool EmailSpecified { get; set; }
    public bool Active { get; set; }
    [XmlIgnore]
    public bool ActiveSpecified { get; set; }
    public List<string> Roles { get; set; }
    [XmlIgnore]
    public bool RolesSpecified { get; set; }
    public DateTime CreatedDate { get; set; }
    [XmlIgnore]
    public bool CreatedDateSpecified { get; set; }
}

然后手动合并:

Account account = new Account
{
    Email = "james@example.com",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    Roles = new List<string>
    {
        "User",
        "Admin"
    }
};

var xml = @"<Account>
<Active>false</Active>
</Account>";
using (var source = new StringReader(xml))
{
    var serializer = new XmlSerializer(typeof(Account));
    var merge = (Account)serializer.Deserialize(source);

    // this bit could also be done via reflection
    if (merge.ActiveSpecified)
    {
        Console.WriteLine("Merging " + nameof(merge.Active));
        account.Active = merge.Active;
    }
    if (merge.EmailSpecified)
    {
        Console.WriteLine("Merging " + nameof(merge.Email));
        account.Email = merge.Email;
    }
    if (merge.CreatedDateSpecified)
    {
        Console.WriteLine("Merging " + nameof(merge.CreatedDate));
        account.CreatedDate = merge.CreatedDate;
    }
    if (merge.RolesSpecified)
    {
        Console.WriteLine("Merging " + nameof(merge.Roles));
        account.Roles = merge.Roles;
    }
}