问题
i have a class and wish to serialize it into xml. the class contains a dictionary.. switched it to a serializeable version (with writexml / readxml).
the problem is that when the dictionary parameter gets serialized.. it wraps the dictionary elements with a parent element "Attributes" and i dont want that.
Example:
public class Product
{
public String Identifier{ get; set; }
[XmlElement]
public SerializableDictionary<string,string> Attributes { get; set; } //custom serializer
}
This Product class gets put in a List structure, then the whole thing serialized, resulting to:
<Products>
<Product>
<Identifier>12345</Identifier>
<Attributes>
<key1> value 1</key1>
<key2> value 2</key2>
</Attributes>
</Product>
</Products>
Id like to not have the node wrapper.
Im using a Serialized Dictionary class that goes around, but through its WriteXml im only able to influence the key value pairs.. not the parent element.
Any self sufficient examples that i could plug to say linqpad would be great.. Heres a short version of the serializable dictionary..
[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
}
回答1:
If you don't want the <Attributes>
element, you need to move the WriteXml
method to the Product
-class.
public void WriteXml(XmlWriter writer)
{
writer.WriteElementString("Identifier", Identifier.ToString("d"));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in Attributes.Keys)
{
writer.WriteStartElement(key.ToString());
TValue value = Attributes[key];
if (value == null)
writer.WriteValue(String.Empty); //render empty ones.
else
writer.WriteValue(value.ToString());
writer.WriteEndElement();
}
}
回答2:
Attributes is the name here of the dictionary key value pair. If that is not there, you won't really be able to deserialize it back to a dictionary.
来源:https://stackoverflow.com/questions/12856456/c-sharp-serialize-dictionary-parameter-without-parent-node