I am serializing data into xml by converting Dictionary into List.
The serialization is ok.
Is it possible to populate dictionary on deserialization? (right now I populate dictionary after deserialization completes and list is returned )
[Serializable]
public class Attribute
{
public string Key { get; set; }
public int Value1 { get; set; }
public int Value2 { get; set; }
public int Value3 { get; set; }
public Attribute() { }
public Attribute(string key, int value1, int value2, int value3)
{
Key = key;
Value1 = value1;
Value2 = value2;
Value3 = value3;
}
}
[XmlRoot("Container")]
public class TestObject
{
public TestObject() { }
private Dictionary<string, Attribute> dictionary = new Dictionary<string, Attribute>();
[XmlIgnore()]
public Dictionary<string, Attribute> Dictionary
{
set { dictionary = value; }
get { return dictionary; }
}
public string Str { get; set; }
private List<Attribute> _attributes = new List<Attribute>();
public List<Attribute> Attributes
{
get
{
if (Dictionary.Count>0)
{
foreach (string key in Dictionary.Keys)
{
_attributes.Add(new Attribute(key, Dictionary[key].Value1, Dictionary[key].Value2, Dictionary[key].Value3));
}
return _attributes;
}
return _attributes;
}
}
}
Code:
TestObject TestObj = new TestObject();
TestObj.Dictionary.Add("asdsad", new Attribute { Value1 = 232, Value2 = 12, Value3 = 89 });
TestObj.Dictionary.Add("sdfer", new Attribute { Value1 = 10, Value2 = 7, Value3 = 857 });
TestObj.Dictionary.Add("zxcdf", new Attribute { Value1 = 266, Value2 = 85, Value3 = 11 });
TestObj.Str = "Test";
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
XmlSerializer serializer = new XmlSerializer(typeof(TestObject));
using (XmlWriter writer = XmlWriter.Create(@"C:\test.xml", settings))
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
serializer.Serialize(writer, TestObj, namespaces);
}
TestObject newob;
using (TextReader textReader = new StreamReader(@"C:\test.xml"))
{
newob = (TestObject)serializer.Deserialize(textReader);
//repopulate dictionary from Attribute list
foreach (Attribute atr in newob.Attributes)
{
//code
}
}