问题
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