空Dictionary<int, string>
如何使用XML中的键和值填充它,如
<items>
<item id='int_goes_here' value='string_goes_here'/>
</items>
并将其序列化为不使用XElement的XML?
答案 0 :(得分:96)
借助临时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"));
答案 1 :(得分:28)
Paul Welter的ASP.NET blog有一个可序列化的字典。但它不使用属性。我将在代码下面解释原因。
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue>
: Dictionary<TKey, TValue>, IXmlSerializable
{
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
#endregion
}
首先,这个代码有一个问题。假设您从其他来源读取字典:
<dictionary>
<item>
<key>
<string>key1</string>
</key>
<value>
<string>value1</string>
</value>
</item>
<item>
<key>
<string>key1</string>
</key>
<value>
<string>value2</string>
</value>
</item>
</dictionary>
这将在de-seariazation上抛出异常,因为你只能有一个字典的密钥。
您必须在序列化词典中使用XElement的原因是词典未定义为Dictionary<String,String>
,词典为Dictionary<TKey,TValue>
。
要查看问题,请问自己:让我们说我们有一个TValue
序列化到使用Elements的东西,它将自己描述为XML(比如词典Dictionary<int,Dictionary<int,string>>
(不是那个)不常见的模式,它是一个查找表)),你的仅属性版本如何完全代表一个属性内的字典?
答案 2 :(得分:6)
默认情况下,字典在C#中不是Serializable,我不知道为什么,但它似乎是一个设计选择。
现在,我建议使用Json.NET将其转换为JSON并从那里转换为字典(反之亦然)。除非你真的需要XML,否则我建议你完全使用JSON。
答案 3 :(得分:3)
基于L.B.的答案。
用法:
var serializer = new DictionarySerializer<string, string>();
serializer.Serialize("dictionary.xml", _dictionary);
_dictionary = _titleDictSerializer.Deserialize("dictionary.xml");
通用类:
public class DictionarySerializer<TKey, TValue>
{
[XmlType(TypeName = "Item")]
public class Item
{
[XmlAttribute("key")]
public TKey Key;
[XmlAttribute("value")]
public TValue Value;
}
private XmlSerializer _serializer = new XmlSerializer(typeof(Item[]), new XmlRootAttribute("Dictionary"));
public Dictionary<TKey, TValue> Deserialize(string filename)
{
using (FileStream stream = new FileStream(filename, FileMode.Open))
using (XmlReader reader = XmlReader.Create(stream))
{
return ((Item[])_serializer.Deserialize(reader)).ToDictionary(p => p.Key, p => p.Value);
}
}
public void Serialize(string filename, Dictionary<TKey, TValue> dictionary)
{
using (var writer = new StreamWriter(filename))
{
_serializer.Serialize(writer, dictionary.Select(p => new Item() { Key = p.Key, Value = p.Value }).ToArray());
}
}
}
答案 4 :(得分:3)
我有一个结构KeyValuePairSerializable
:
[Serializable]
public struct KeyValuePairSerializable<K, V>
{
public KeyValuePairSerializable(KeyValuePair<K, V> pair)
{
Key = pair.Key;
Value = pair.Value;
}
[XmlAttribute]
public K Key { get; set; }
[XmlText]
public V Value { get; set; }
public override string ToString()
{
return "[" + StringHelper.ToString(Key, "") + ", " + StringHelper.ToString(Value, "") + "]";
}
}
然后,Dictionary
属性的XML序列化由:
[XmlIgnore]
public Dictionary<string, string> Parameters { get; set; }
[XmlArray("Parameters")]
[XmlArrayItem("Pair")]
[DebuggerBrowsable(DebuggerBrowsableState.Never)] // not necessary
public KeyValuePairSerializable<string, string>[] ParametersXml
{
get
{
return Parameters?.Select(p => new KeyValuePairSerializable<string, string>(p)).ToArray();
}
set
{
Parameters = value?.ToDictionary(i => i.Key, i => i.Value);
}
}
该属性必须是数组,而不是List。
答案 5 :(得分:2)
编写一个类A,它包含一个B类数组.B类应该有一个id属性和一个value属性。将xml反序列化为类A.将A中的数组转换为所需的字典。
要序列化字典,请将其转换为A类实例,并序列化...
答案 6 :(得分:2)
您可以使用ExtendedXmlSerializer。 如果你有一个班级:
public class TestClass
{
public Dictionary<int, string> Dictionary { get; set; }
}
并创建此类的实例:
var obj = new TestClass
{
Dictionary = new Dictionary<int, string>
{
{1, "First"},
{2, "Second"},
{3, "Other"},
}
};
您可以使用ExtendedXmlSerializer序列化此对象:
var serializer = new ConfigurationContainer()
.UseOptimizedNamespaces() //If you want to have all namespaces in root element
.Create();
var xml = serializer.Serialize(
new XmlWriterSettings { Indent = true }, //If you want to formated xml
obj);
输出xml如下所示:
<?xml version="1.0" encoding="utf-8"?>
<TestClass xmlns:sys="https://extendedxmlserializer.github.io/system" xmlns:exs="https://extendedxmlserializer.github.io/v2" xmlns="clr-namespace:ExtendedXmlSerializer.Samples;assembly=ExtendedXmlSerializer.Samples">
<Dictionary>
<sys:Item>
<Key>1</Key>
<Value>First</Value>
</sys:Item>
<sys:Item>
<Key>2</Key>
<Value>Second</Value>
</sys:Item>
<sys:Item>
<Key>3</Key>
<Value>Other</Value>
</sys:Item>
</Dictionary>
</TestClass>
您可以从nuget安装ExtendedXmlSerializer或运行以下命令:
Install-Package ExtendedXmlSerializer
答案 7 :(得分:2)
KeyedCollection的工作方式类似于字典,并且可以序列化。
首先创建一个包含键和值的类:
/// <summary>
/// simple class
/// </summary>
/// <remarks></remarks>
[Serializable()]
public class cCulture
{
/// <summary>
/// culture
/// </summary>
public string culture;
/// <summary>
/// word list
/// </summary>
public List<string> list;
/// <summary>
/// status
/// </summary>
public string status;
}
然后创建KeyedCollection类型的类,并将该类的属性定义为键。
/// <summary>
/// keyed collection.
/// </summary>
/// <remarks></remarks>
[Serializable()]
public class cCultures : System.Collections.ObjectModel.KeyedCollection<string, cCulture>
{
protected override string GetKeyForItem(cCulture item)
{
return item.culture;
}
}
使用full来序列化此类数据。
答案 8 :(得分:1)
我使用可序列化的类来进行不同模块之间的WCF通信。 下面是一个可序列化类的示例,它也用作DataContract。 我的方法是使用LINQ的强大功能将Dictionary转换为开箱即用的可序列化List&lt;&gt; KeyValuePair&lt;&gt;:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace MyFirm.Common.Data
{
[DataContract]
[Serializable]
public class SerializableClassX
{
// since the Dictionary<> class is not serializable,
// we convert it to the List<KeyValuePair<>>
[XmlIgnore]
public Dictionary<string, int> DictionaryX
{
get
{
return SerializableList == null ?
null :
SerializableList.ToDictionary(item => item.Key, item => item.Value);
}
set
{
SerializableList = value == null ?
null :
value.ToList();
}
}
[DataMember]
[XmlArray("SerializableList")]
[XmlArrayItem("Pair")]
public List<KeyValuePair<string, int>> SerializableList { get; set; }
}
}
用法很简单 - 我将字典分配给我的数据对象的字典字段 - DictionaryX。 SerializableClassX内部通过将分配的字典转换为可序列化的List&lt;&gt;来支持序列化。 KeyValuePair&lt;&gt;:
// create my data object
SerializableClassX SerializableObj = new SerializableClassX(param);
// this will call the DictionaryX.set and convert the '
// new Dictionary into SerializableList
SerializableObj.DictionaryX = new Dictionary<string, int>
{
{"Key1", 1},
{"Key2", 2},
};
答案 9 :(得分:0)
Sharpeserializer(开源)有一个简单的方法:
http://www.sharpserializer.com/
它可以直接序列化/反序列化字典。
无需使用任何属性标记对象,也不必在Serialize方法中提供对象类型(请参阅here)。
通过nuget安装:Install-package sharpserializer
然后很简单:
Hello World (来自官方网站):
// create fake obj
var obj = createFakeObject();
// create instance of sharpSerializer
// with standard constructor it serializes to xml
var serializer = new SharpSerializer();
// serialize
serializer.Serialize(obj, "test.xml");
// deserialize
var obj2 = serializer.Deserialize("test.xml");