考虑一个场景,其中您有一个 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中文网其他相关文章!