我继承了一个c#类。我已经成功地“构建”了对象。但是我需要将对象序列化为XML。有什么简单的方法吗?
看起来类已经为序列化设置了,但我不确定如何获得XML表示。我的类定义是这样的:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.domain.com/test")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.domain.com/test", IsNullable = false)]
public partial class MyObject
{
...
}
以下是我认为我能做的,但它不起作用:
MyObject o = new MyObject();
// Set o properties
string xml = o.ToString();
如何获得该对象的XML表示形式?
可以将下面的函数复制到任何对象,以使用System.Xml名称空间添加XML保存函数。
/// <summary>
/// Saves to an xml file
/// </summary>
/// <param name="FileName">File path of the new xml file</param>
public void Save(string FileName)
{
using (var writer = new System.IO.StreamWriter(FileName))
{
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(writer, this);
writer.Flush();
}
}
要从保存的文件创建对象,添加以下函数并将[ObjectType]替换为要创建的对象类型。
/// <summary>
/// Load an object from an xml file
/// </summary>
/// <param name="FileName">Xml file name</param>
/// <returns>The object created from the xml file</returns>
public static [ObjectType] Load(string FileName)
{
using (var stream = System.IO.File.OpenRead(FileName))
{
var serializer = new XmlSerializer(typeof([ObjectType]));
return serializer.Deserialize(stream) as [ObjectType];
}
}