开发者

XmlSerializer saves null-file

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:

XmlSerializer saves null-file

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 GetMyDataObj开发者_StackOverflow中文版ect()
        {
            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;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜