如何从不使用 XElement 的自定义 XML 序列化/反序列化为 `Dictionary<int, string>`? [英] How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

查看:17
本文介绍了如何从不使用 XElement 的自定义 XML 序列化/反序列化为 `Dictionary<int, string>`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有空的 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&lt;int, string&gt;`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆