C# 如何用XML序列化字典
我可以通过以下方式序列化IEnumerable:C# 如何用XML序列化字典,c#,.net,xml-serialization,xmlserializer,C#,.net,Xml Serialization,Xmlserializer,我可以通过以下方式序列化IEnumerable: [XmlArray("TRANSACTIONS")] [XmlArrayItem("TRANSACTION", typeof(Record))] public IEnumerable<BudgetRecord> Records { get { foreach(Record br in _budget) { yield return br; }
[XmlArray("TRANSACTIONS")]
[XmlArrayItem("TRANSACTION", typeof(Record))]
public IEnumerable<BudgetRecord> Records
{
get
{
foreach(Record br in _budget)
{
yield return br;
}
}
}
[XmlArray(“事务”)]
[XmlArrayItem(“交易”,类型(记录))]
公共数字记录
{
得到
{
foreach(在预算中记录br)
{
收益率br;
}
}
}
然而,我意识到现在我需要一个包含集合字典(RecordCollection实现IEnumerable)的字典
我怎样才能做到这一点呢?看看下面的博文
这个(不是英文的,但是代码很有用)
代码示例来源:
使用System.Collections.Generic;
使用系统集合;
使用System.IO;
使用System.Xml.Serialization;
使用System.Xml;
使用制度;
公共静态void序列化(TextWriter、IDictionary dictionary)
{
列表条目=新列表(dictionary.Count);
foreach(dictionary.Keys中的对象键)
{
添加(新条目(键,字典[key]);
}
XmlSerializer serializer=新的XmlSerializer(typeof(List));
序列化器。序列化(编写器、条目);
}
公共静态void反序列化(TextReader,IDictionary dictionary)
{
dictionary.Clear();
XmlSerializer serializer=新的XmlSerializer(typeof(List));
列表=(列表)序列化程序。反序列化(读取器);
foreach(列表中的条目)
{
dictionary[entry.Key]=entry.Value;
}
}
公开课入学
{
公开对象密钥;
公共客体价值;
公众进入()
{
}
公共条目(对象键、对象值)
{
钥匙=钥匙;
价值=价值;
}
}
当键和值是字符串时,它生成如下输出
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfEntry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Entry>
<Key xsi:type="xsd:string">MyKey</Key>
<Value xsi:type="xsd:string">MyValue</Value>
</Entry>
<Entry>
<Key xsi:type="xsd:string">MyOtherKey</Key>
<Value xsi:type="xsd:string">MyOtherValue</Value>
</Entry>
</ArrayOfEntry>
美奇钥匙
我的价值
肌肉疗法
肌酐值
我已经用了一段时间了。它最初来自于
命名空间序列化字典
{
使用制度;
使用System.Collections.Generic;
使用System.Runtime.Serialization;
使用System.Xml;
使用System.Xml.Schema;
使用System.Xml.Serialization;
///
///表示键和值的XML可序列化集合。
///
///字典中键的类型。
///字典中值的类型。
[可序列化]
[XmlRoot(“字典”)]
公共类SerializableDictionary:Dictionary,IXmlSerializable
{
///
///项目的默认XML标记名。
///
private const string DefaultItemTag=“item”;
///
///键的默认XML标记名。
///
private const string DefaultKeyTag=“key”;
///
///值的默认XML标记名。
///
private const string DefaultValueTag=“value”;
///
///密钥类型的XML序列化程序。
///
私有静态只读XmlSerializer keySerializer=新XmlSerializer(typeof(TKey));
///
///值类型的XML序列化程序。
///
私有静态只读XmlSerializer valueSerializer=新XmlSerializer(typeof(TValue));
///
///初始化的新实例
///班级。
///
公共序列化字典()
{
}
///
///初始化的新实例
///班级。
///
///A
///反对
///包含序列化所需的信息
/// .
///
///A
///结构
///包含序列化流的源和目标
///与
/// .
///
受保护的SerializableDictionary(SerializationInfo,StreamingContext上下文):基本(信息,上下文)
{
}
///
///获取项的XML标记名。
///
受保护的虚拟字符串ItemTagName
{
得到
{
返回DefaultItemTag;
}
}
///
///获取键的XML标记名。
///
受保护的虚拟字符串键标记名
{
得到
{
返回DefaultKeyTag;
}
}
///
///获取值的XML标记名。
///
受保护的虚拟字符串ValueTagName
{
得到
{
返回DefaultValueTag;
}
}
///
///获取XML序列化的XML架构。
///
///序列化对象的XML架构。
公共XmlSchema GetSchema()
{
返回null;
}
///
///从XML反序列化对象。
///
///对象的XML表示形式。
公共void ReadXml(XmlReader)
{
var waspempty=reader.IsEmptyElement;
reader.Read();
如果(为空)
{
返回;
}
尝试
{
while(reader.NodeType!=XmlNodeType.EndElement)
{
此.ReadItem(读取器);
reader.MoveToContent();
}
}
最后
{
reader.ReadEndElement();
}
}
///
///将此实例序列化为XML。
///
///要序列化到的XML编写器。
public void WriteXml(XmlWriter)
{
foreach(此字段中的var keyValuePair)
{
this.WriteItem(writer,keyValuePair);
}
}
///
///反序列化字典项。
///
///对象的XML表示形式。
私有void ReadItem(XmlReader)
{
reader.ReadStartElement(此.ItemTagName);
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfEntry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Entry>
<Key xsi:type="xsd:string">MyKey</Key>
<Value xsi:type="xsd:string">MyValue</Value>
</Entry>
<Entry>
<Key xsi:type="xsd:string">MyOtherKey</Key>
<Value xsi:type="xsd:string">MyOtherValue</Value>
</Entry>
</ArrayOfEntry>
namespace SerializeDictionary
{
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
/// <summary>
/// Represents an XML serializable collection of keys and values.
/// </summary>
/// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
[Serializable]
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
/// <summary>
/// The default XML tag name for an item.
/// </summary>
private const string DefaultItemTag = "item";
/// <summary>
/// The default XML tag name for a key.
/// </summary>
private const string DefaultKeyTag = "key";
/// <summary>
/// The default XML tag name for a value.
/// </summary>
private const string DefaultValueTag = "value";
/// <summary>
/// The XML serializer for the key type.
/// </summary>
private static readonly XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
/// <summary>
/// The XML serializer for the value type.
/// </summary>
private static readonly XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
/// <summary>
/// Initializes a new instance of the
/// <see cref="SerializableDictionary<TKey, TValue>"/> class.
/// </summary>
public SerializableDictionary()
{
}
/// <summary>
/// Initializes a new instance of the
/// <see cref="SerializableDictionary<TKey, TValue>"/> class.
/// </summary>
/// <param name="info">A
/// <see cref="T:System.Runtime.Serialization.SerializationInfo"/> object
/// containing the information required to serialize the
/// <see cref="T:System.Collections.Generic.Dictionary`2"/>.
/// </param>
/// <param name="context">A
/// <see cref="T:System.Runtime.Serialization.StreamingContext"/> structure
/// containing the source and destination of the serialized stream
/// associated with the
/// <see cref="T:System.Collections.Generic.Dictionary`2"/>.
/// </param>
protected SerializableDictionary(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
/// <summary>
/// Gets the XML tag name for an item.
/// </summary>
protected virtual string ItemTagName
{
get
{
return DefaultItemTag;
}
}
/// <summary>
/// Gets the XML tag name for a key.
/// </summary>
protected virtual string KeyTagName
{
get
{
return DefaultKeyTag;
}
}
/// <summary>
/// Gets the XML tag name for a value.
/// </summary>
protected virtual string ValueTagName
{
get
{
return DefaultValueTag;
}
}
/// <summary>
/// Gets the XML schema for the XML serialization.
/// </summary>
/// <returns>An XML schema for the serialized object.</returns>
public XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// Deserializes the object from XML.
/// </summary>
/// <param name="reader">The XML representation of the object.</param>
public void ReadXml(XmlReader reader)
{
var wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
{
return;
}
try
{
while (reader.NodeType != XmlNodeType.EndElement)
{
this.ReadItem(reader);
reader.MoveToContent();
}
}
finally
{
reader.ReadEndElement();
}
}
/// <summary>
/// Serializes this instance to XML.
/// </summary>
/// <param name="writer">The XML writer to serialize to.</param>
public void WriteXml(XmlWriter writer)
{
foreach (var keyValuePair in this)
{
this.WriteItem(writer, keyValuePair);
}
}
/// <summary>
/// Deserializes the dictionary item.
/// </summary>
/// <param name="reader">The XML representation of the object.</param>
private void ReadItem(XmlReader reader)
{
reader.ReadStartElement(this.ItemTagName);
try
{
this.Add(this.ReadKey(reader), this.ReadValue(reader));
}
finally
{
reader.ReadEndElement();
}
}
/// <summary>
/// Deserializes the dictionary item's key.
/// </summary>
/// <param name="reader">The XML representation of the object.</param>
/// <returns>The dictionary item's key.</returns>
private TKey ReadKey(XmlReader reader)
{
reader.ReadStartElement(this.KeyTagName);
try
{
return (TKey)keySerializer.Deserialize(reader);
}
finally
{
reader.ReadEndElement();
}
}
/// <summary>
/// Deserializes the dictionary item's value.
/// </summary>
/// <param name="reader">The XML representation of the object.</param>
/// <returns>The dictionary item's value.</returns>
private TValue ReadValue(XmlReader reader)
{
reader.ReadStartElement(this.ValueTagName);
try
{
return (TValue)valueSerializer.Deserialize(reader);
}
finally
{
reader.ReadEndElement();
}
}
/// <summary>
/// Serializes the dictionary item.
/// </summary>
/// <param name="writer">The XML writer to serialize to.</param>
/// <param name="keyValuePair">The key/value pair.</param>
private void WriteItem(XmlWriter writer, KeyValuePair<TKey, TValue> keyValuePair)
{
writer.WriteStartElement(this.ItemTagName);
try
{
this.WriteKey(writer, keyValuePair.Key);
this.WriteValue(writer, keyValuePair.Value);
}
finally
{
writer.WriteEndElement();
}
}
/// <summary>
/// Serializes the dictionary item's key.
/// </summary>
/// <param name="writer">The XML writer to serialize to.</param>
/// <param name="key">The dictionary item's key.</param>
private void WriteKey(XmlWriter writer, TKey key)
{
writer.WriteStartElement(this.KeyTagName);
try
{
keySerializer.Serialize(writer, key);
}
finally
{
writer.WriteEndElement();
}
}
/// <summary>
/// Serializes the dictionary item's value.
/// </summary>
/// <param name="writer">The XML writer to serialize to.</param>
/// <param name="value">The dictionary item's value.</param>
private void WriteValue(XmlWriter writer, TValue value)
{
writer.WriteStartElement(this.ValueTagName);
try
{
valueSerializer.Serialize(writer, value);
}
finally
{
writer.WriteEndElement();
}
}
}
}
[XmlElement("Dictionary")]
public List<KeyValuePair<string, string>> XMLDictionaryProxy
{
get
{
return new List<KeyValuePair<string, string>>(this.Dictionary);
}
set
{
this.Dictionary = new Dictionary<string, string>();
foreach (var pair in value)
this.Dictionary[pair.Key] = pair.Value;
}
}
[XmlIgnore]
public Dictionary<string, string> Dictionary
{
get; set;
}
static class Program
{
static void Main(string[] args)
{
{
// create a tax table and save it to a file
var tax = ProgressiveTax.PAYE();
File.WriteAllText("PAYE.xml", tax.ToXml());
}
{
// read a tax table from a file
var tax = ProgressiveTax.FromXml(File.ReadAllText("PAYE.xml"));
// use the tax table
var x = tax.Evaluate(42250m);
Debug.WriteLine($"Tax={x}");
}
}
}
<?xml version="1.0" encoding="utf-16"?>
<ProgressiveTax xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Credit="2400">
<Brackets>
<Bracket>
<Item1>0</Item1>
<Item2>0.1</Item2>
</Bracket>
<Bracket>
<Item1>24000</Item1>
<Item2>0.15</Item2>
</Bracket>
<Bracket>
<Item1>40667</Item1>
<Item2>0.2</Item2>
</Bracket>
<Bracket>
<Item1>57334</Item1>
<Item2>0.25</Item2>
</Bracket>
</Brackets>
</ProgressiveTax>
public class ProgressiveTax
{
public ProgressiveTax()
{
this.Table = new SortedDictionary<decimal, float>();
}
public ProgressiveTax(SortedDictionary<decimal, float> table)
{
this.Table = table;
}
public static ProgressiveTax PAYE()
{
var tax = new ProgressiveTax();
tax.Credit = 2400m;
tax.Table[0m] = 0.1f;
tax.Table[24000m] = 0.15f;
tax.Table[40667m] = 0.20f;
tax.Table[57334m] = 0.25f;
return tax;
}
public string ToXml()
{
var fs = new StringWriter();
var xs = new XmlSerializer(typeof(ProgressiveTax));
xs.Serialize(fs, this);
fs.Close();
return fs.ToString();
}
public static ProgressiveTax FromXml(string xml)
{
var fs = new StringReader(xml);
var xs = new XmlSerializer(typeof(ProgressiveTax));
var tax = xs.Deserialize(fs) as ProgressiveTax;
fs.Close();
return tax;
}
[XmlAttribute]
public decimal Credit { get; set; }
[XmlIgnore()]
SortedDictionary<decimal, float> Table { get; }
[XmlArrayItem(ElementName = "Bracket")]
public (decimal lower, float rate)[] Brackets
{
get
{
var parts = new (decimal lower, float rate)[Table.Count];
int index = 0;
foreach (var item in Table)
{
parts[index++] = (item.Key, item.Value);
}
return parts;
}
set
{
Table.Clear();
foreach (var (lower, rate) in value)
{
Table[lower] = rate;
}
}
}
public decimal Evaluate(decimal income)
{
decimal result = -Credit;
foreach (var item in Table.Reverse())
{
if (item.Key <= income)
{
Debug.WriteLine($"Assess {item.Value:P2} tax on {income - item.Key}");
result += (decimal)( item.Value * (float) (income - item.Key));
income = item.Key;
}
}
return Math.Max(0m, result);
}
}
Assess 20.00% tax on 1583
Assess 15.00% tax on 16667
Assess 10.00% tax on 24000
Tax=2816.65