I have a problem with serializing my objects. I implemented IXmlSerializable interface and initialize object of XmlSerializer(for example, serializer). But sometimes after calling serializer.Serialize(writer, data) my output file looks like this:
why do I have such behavior?
public class MyClass : IData
{
private static readonly XmlSerializer _formatter = new XmlSerializer(typeof(MyData));
public void Save(string filePath)
{
using (StreamWriter writer = new StreamWriter(filePath))
{
Save(writer);
writer.Close();
}
}
public void Save(TextWriter Writer)
{
MyData data = GetMyDataObject();
_formatter.Serialize(Writer, data);
}
private MyData GetMyDataObject()
{
MyData data = new MyData ();
foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(IData)))
pd.SetValue(data, pd.GetValue(this));
return data;
}
}
public class MyData : IData, IXmlSerializable
{
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteAttributeString("Number", Number);
if (HardwareInformation != null)
{
writer.WriteStartElement("HWInfoList");
foreach (KeyValuePair<string, string> kw in HardwareInformation)
{
writer.WriteStartElement("HWInfo");
writer.WriteAttributeString("Key", kw.Key);
writer.WriteAttributeString("Value", kw.Value);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}
}
public interface IData
{
Dictionary<string, string> HardwareInformation { get; set; }
string Number { get; set; }
}
How are you serializing? Here is an example of a Serialize Function
private XDocument Serialize<T>(object obj)
{
XDocument ReturnValue = new XDocument();
XmlSerializer Serializer = new XmlSerializer(typeof(T));
System.IO.StringWriter sw = new System.IO.StringWriter();
System.IO.StringReader sr;
Serializer.Serialize(sw, obj);
sr = new System.IO.StringReader(sw.ToString());
ReturnValue = XDocument.Load(sr);
return ReturnValue;
}
来源:https://stackoverflow.com/questions/7635519/xmlserializer-saves-null-file