栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何序列化/反序列化为字典`来自自定义XML而不使用XElement?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何序列化/反序列化为字典`来自自定义XML而不使用XElement?

在一个临时

item
班的帮助下

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"));


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/576140.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号