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