XmlSerializer 保存空文件
我在序列化对象时遇到问题。 我实现了 IXmlSerialized 接口并初始化 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; }
}
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; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你如何进行序列化?这是序列化函数的示例
How are you serializing? Here is an example of a Serialize Function