简体   繁体   中英

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">test@test.com</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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM