【问题标题】:Populate Object from XML从 XML 填充对象
【发布时间】:2019-08-20 04:24:18
【问题描述】:

我有一个这样的对象:

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>

谢谢

【问题讨论】:

    标签: c# json xml dto populate


    【解决方案1】:

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

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

    然后EmailSpecified a:控制Email 是否被序列化,并且b:当从活动值反序列化时,它被分配true 的值。所以:你可以这样做:

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

    【讨论】:

    • 您的方法创建了一个新对象。我需要使用 XML 填充现有对象,例如
    • @LucaRomagnoli 见最后一段;您正在寻找的是一个合并 API,但这不是内置的。我有一个关于如何让它更易于管理的想法,不过……一会儿……
    • @LucaRomagnoli 查看编辑;我认为这应该让你排序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    相关资源
    最近更新 更多