Sergey
Sergey

Reputation: 8071

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.

Upvotes: 1

Views: 2314

Answers (1)

Alex Filipovici
Alex Filipovici

Reputation: 32541

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

Upvotes: 3

Related Questions