我有一个类并希望将其序列化为 xml。该类包含一个字典..将其切换为可序列化版本(使用 writexml / readxml)。
问题是当字典参数被序列化时..它用父元素“属性”包装字典元素,我不想要那个。
例子:
public class Product
{
public String Identifier{ get; set; }
[XmlElement]
public SerializableDictionary<string,string> Attributes { get; set; } //custom serializer
}
这个 Product 类被放入一个 List 结构中,然后整个序列化,结果是:
<Products>
<Product>
<Identifier>12345</Identifier>
<Attributes>
<key1> value 1</key1>
<key2> value 2</key2>
</Attributes>
</Product>
</Products>
我想没有节点包装器。
我使用了一个序列化的字典类,但是通过它的 WriteXml 我只能影响键值对..而不是父元素。
任何我可以插入说linqpad的自给自足的例子都会很棒..这是可序列化字典的简短版本..
[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)
{
//not including for the sake of brevity
}
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(key.ToString());
TValue value = this[key];
if (value == null)
writer.WriteValue(String.Empty); //render empty ones.
else
writer.WriteValue(value.ToString());
writer.WriteEndElement();
}
}
#endregion
}