如何通过属性名称和内部xml反序列化属性 [英] How to deserialize to property by attribute name and inner xml

查看:188
本文介绍了如何通过属性名称和内部xml反序列化属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的xml:

<employees>
  <employee id="11629">
   <field id="displayName">First Last</field>
   <field id="email">test@test.com</field>
  </employee>
</employees>

我创建了一个类:

public class Employee
{
    [XmlAttribute("id")]
    public string Id { get; set; }

    public string DisplayName { get; set; }

    public string Email { get; set; }
}

对于Id,一切正常,但我不知道如何属性,我们可以将值设置为DisplayName属性。

For Id everything works perfectly, but I can't figure out how but attribute we can set value to DisplayName property.

请帮助。

推荐答案

您可以尝试以下方法:

public class Employee
{
    [XmlAttribute("id")]
    public string Id { get; set; }

    [XmlElement("field")]
    public List<Field> Fields { get; set; }

    public string DisplayName 
    { 
        get 
        {
            return Fields.Where(i => i.Id == "displayName").FirstOrDefault().Value;
        } 
    }

    public string Email
    {
        get
        {
            return Fields.Where(i => i.Id == "email").FirstOrDefault().Value;
        }
    }
}

public class Field
{
    [XmlAttribute("id")]
    public string Id { get; set; }

    [XmlText]
    public string Value { get; set; }
}

这篇关于如何通过属性名称和内部xml反序列化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆