'How to deserialize to property by attribute name and inner xml

I have an xml like this:

<employees>
  <employee id="11629">
   <field id="displayName">First Last</field>
   <field id="email">[email protected]</field>
  </employee>
</employees>

and I created a class:

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

    public string DisplayName { get; set; }

    public string Email { get; set; }
}

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

Please help.



Solution 1:[1]

You may try this:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1