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>`?
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
