c# - 从 XML 填充对象

标签 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>

谢谢

最佳答案

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

关于c# - 从 XML 填充对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55413853/

相关文章:

c# - 将委托(delegate)传递给事件 c#

c# - 使所有表单都可以访问表单功能

python - 确保 POST 数据是有效的 JSON

javascript - JS 中的 fetch 未从 php 中的 json_encode 接收到适当的 JSON 格式

android - 图标 View 中的弹出菜单..?

c# - 如何在不同线程中同时使用队列

c# - 如何通过 C# 在 powershell 中传递一个应该为 $null 的参数

php - Highstock mysql json 多条数据

java - 从子元素创建 XPath

android - 可绘制的android XML周围出现奇怪的黑色边框