XmlSerializer saves null-file

泄露秘密 提交于 2019-12-08 02:49:43

问题


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; }
}

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!