从定制XML不使用的XElement';如何序列化/反序列化到`字典< INT,字符串&GT? [英] How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

查看:197
本文介绍了从定制XML不使用的XElement';如何序列化/反序列化到`字典< INT,字符串&GT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有空词典< INT,字符串> 如何与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?

推荐答案

通过临时项目类的帮助

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 的,如果你改变了主意。

------------------------------------------------------------------------------

Here is how it can be done using XElement, if you change your mind.

序列化

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

这篇关于从定制XML不使用的XElement';如何序列化/反序列化到`字典&LT; INT,字符串&GT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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