How to deserialize to property by attribute name and inner xml

六月ゝ 毕业季﹏ 提交于 2019-12-13 17:38:12

问题


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.


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


来源:https://stackoverflow.com/questions/14279665/how-to-deserialize-to-property-by-attribute-name-and-inner-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!