我在序列化对象时遇到问题。 我实现了IXmlSerializable接口并初始化XmlSerializer的对象(例如,序列化器)。 但有时在调用serializer.Serialize(writer,data)后,我的输出文件如下所示:
为什么我会有这样的行为?
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; }
}
答案 0 :(得分:0)
你是如何序列化的?以下是序列化函数的示例
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;
}