How to serialize/deserialize to `Dictionarylt;int, stringgt;` from custom XML not using XElement?(如何从不使用 XElement 的自定义 XML 序列化/反序列化为 `Dictionarylt;int, stringgt;`?)
问题描述
有空的 Dictionary<int, string>
如何用 XML 中的键和值填充它,例如
Having empty Dictionary<int, string>
how to fill it with keys and values from XML like
<items>
<item id='int_goes_here' value='string_goes_here'/>
</items>
并在不使用 XElement 的情况下将其序列化回 XML?
and serialize it back into XML not using 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"));
这篇关于如何从不使用 XElement 的自定义 XML 序列化/反序列化为 `Dictionary<int, string>`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从不使用 XElement 的自定义 XML 序列化/反序列化为 `Dictionary<int, string>`?


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01