Deserialising XML based on attribute values

倖福魔咒の 提交于 2020-01-06 18:09:00

问题


I have some XML that I need to deserialise

<element>
  <childElement key="myKey1">a value</childElement>
  <childElement key="myKey2">another value</childElement>
</element>

Into a class like

[XmlRoot(ElementName="element")]
public class Element
{
  public string MyKey1 { get; set; }
  public string MyKey2 { get; set; }
}

Is it possible for me to annotate MyKey1 and MyKey2 so that if the xml above is deserialised then MyKey1 will be "a value" and MyKey2 will equal "another value"? If not then what is the best approach to deserialising attributes like this?


回答1:


You can use XmlAttribute attribute but your xml seems better to fit to a Dictionary<string,string>

Using Linq To Xml

string xml = @"<element>
    <childElement key=""myKey1"">a value</childElement>
    <childElement key=""myKey2"">another value</childElement>
</element>";

var xDoc = XDocument.Parse(xml);
var dict = xDoc.Descendants("childElement")
               .ToDictionary(x => x.Attribute("key").Value, x => x.Value);

Console.WriteLine(dict["myKey1"]);


来源:https://stackoverflow.com/questions/16147748/deserialising-xml-based-on-attribute-values

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