考慮一個場景,其中您有一個Dictionary
<items> <item>
要在不使用XElement 的情況下實現此序列化和反序列化:
public class Item { [XmlAttribute] public int Id; [XmlAttribute] public string Value; }
Dictionary<int, string> dict = new Dictionary<int, string>() { { 1, "one" }, { 2, "two" } };
XmlSerializer serializer = new XmlSerializer(typeof(Item[]), new XmlRootAttribute() { ElementName = "items" });
serializer.Serialize(stream, dict.Select(kv => new Item() { Id = kv.Key, Value = kv.Value }).ToArray());
var orgDict = ((Item[])serializer.Deserialize(stream)) .ToDictionary(i => i.Id, i => i.Value);
使用XElement 的替代方法
XElement xElem = new XElement( "items", dict.Select(x => new XElement("item", new XAttribute("id", x.Key), new XAttribute("value", x.Value))) ); var xml = xElem.ToString(); //xElem.Save(...);序列化
XElement xElem2 = XElement.Parse(xml); //XElement.Load(...) var newDict = xElem2.Descendants("item") .ToDictionary(x => (int)x.Attribute("id"), x => (string)x.Attribute("value"));反序列化
以上是如何在不使用 XElement 的情況下將字典序列化和反序列化為自訂 XML?的詳細內容。更多資訊請關注PHP中文網其他相關文章!