轻松将整个类实例写入XML文件并读取回来

14

我有一个主类名为theGarage,其中包含我们的客户、供应商和任务类的实例。

我想将程序数据保存到一个XML文件中,我使用了下面的代码(只是一个片段,我有针对其他类的相匹配代码)。我想知道是否有更简单的方法可以完成这个任务,例如写整个theGarage类到一个XML文件中,并在不必编写下面的代码的情况下读取它。

   public void saveToFile()
    {
        using (XmlWriter writer = XmlWriter.Create("theGarage.xml"))
        {
            writer.WriteStartDocument();

            ///
            writer.WriteStartElement("theGarage");
            writer.WriteStartElement("Customers");

            foreach (Customer Customer in Program.theGarage.Customers)
            {
                writer.WriteStartElement("Customer");
                writer.WriteElementString("FirstName", Customer.FirstName);
                writer.WriteElementString("LastName", Customer.LastName);
                writer.WriteElementString("Address1", Customer.Address1);
                writer.WriteElementString("Address2", Customer.Address2);
                writer.WriteElementString("Town", Customer.Town);
                writer.WriteElementString("County", Customer.County);
                writer.WriteElementString("PostCode", Customer.Postcode);
                writer.WriteElementString("TelephoneHome", Customer.TelephoneHome);
                writer.WriteElementString("TelephoneMob", Customer.TelephoneMob);

                //begin vehicle list
                writer.WriteStartElement("Vehicles");

                foreach (Vehicle Vehicle in Customer.Cars)
                {
                    writer.WriteStartElement("Vehicle");
                    writer.WriteElementString("Make", Vehicle.Make);
                    writer.WriteElementString("Model", Vehicle.Model);
                    writer.WriteElementString("Colour", Vehicle.Colour);
                    writer.WriteElementString("EngineSize", Vehicle.EngineSize);
                    writer.WriteElementString("Registration", Vehicle.Registration);
                    writer.WriteElementString("Year", Vehicle.YearOfFirstReg);
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }
    }

你正在编写什么类型的应用程序?你只是想为单用户GUI应用程序保存会话吗?否则(例如,如果您正在做一些可以供多个并发用户使用的东西),您可能不希望将信息存储在文件中。即使在单用户场景下,可能有更好的替代方案(如SQLite)来存储数据。 - Paolo Falabella
如果我们有足够的资源,选择将是程序连接到MySQL数据库 - 这是我更熟悉的编程方法。 - developer__c
好的,根据您的情况,有各种“轻量级”选项。如果您能更详细地说明您正在编写什么类型的应用程序,这里的人们将能够建议适合的东西。 - Paolo Falabella
4个回答

47

有一种更简单的序列化对象的方法,可以使用 XmlSerializer。详见此文档

将您的车库序列化到文件的代码片段如下:

var garage = new theGarage();

// TODO init your garage..

XmlSerializer xs = new XmlSerializer(typeof(theGarage));
TextWriter tw = new StreamWriter(@"c:\temp\garage.xml");
xs.Serialize(tw, garage);

并提供从文件加载车库的代码:

using(var sr = new StreamReader(@"c:\temp\garage.xml"))
{
   garage = (theGarage)xs.Deserialize(sr);
}

看了文档链接,这绝对比我一直在做的要简单多了! - developer__c
尝试运行代码时,我在车库上遇到了错误 -“无法序列化,因为它没有无参构造函数。” - developer__c
我仍然无法让它工作,现在出现了一个错误,指出反射存在问题? - developer__c
1
然后查看此答案,很可能需要在不应序列化的字段上使用[XmlIgnore()] - Michal Klouda
排好了,在主类中我有另外三个类的列表 - 这些只需要无参构造函数!非常感谢您的帮助! - developer__c
你也应该在 StreamWriter 上使用 'using'。 - HenrikP

7
那么,加入几个巧妙的扩展方法,你就可以轻松地将数据读/写到文件中了。
public static class Extensions
{
    public static string ToXml(this object obj)
    {
        XmlSerializer s = new XmlSerializer(obj.GetType());
        using (StringWriter writer = new StringWriter())
        {
            s.Serialize(writer, obj);
            return writer.ToString();
        }
    }

    public static T FromXml<T>(this string data)
    {
        XmlSerializer s = new XmlSerializer(typeof(T));
        using (StringReader reader = new StringReader(data))
        {
            object obj = s.Deserialize(reader);
            return (T)obj;
        }
    }
}

例子

 var xmlData = myObject.ToXml();

 var anotherObject = xmlData.FromXml<ObjectType>();

2
我刚刚写了一篇关于将对象数据保存为二进制、XML或Json的博客文章(链接)。这里是将类实例写入和读取到/自XML的函数。更多细节请查看我的博客文章。
需要在项目中包含System.Xml程序集。
/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
    TextWriter writer = null;
    try
    {
        var serializer = new XmlSerializer(typeof(T));
        writer = new StreamWriter(filePath, append);
        serializer.Serialize(writer, objectToWrite);
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}

/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
    TextReader reader = null;
    try
    {
        var serializer = new XmlSerializer(typeof(T));
        reader = new StreamReader(filePath);
        return (T)serializer.Deserialize(reader);
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}

示例
// Write the list of salesman objects to file.
WriteToXmlFile<Customer>("C:\TheGarage.txt", customer);

// Read the list of salesman objects from the file back into a variable.
Customer customer = ReadFromXmlFile<Customer>("C:\TheGarage.txt");

0

在我的项目中,我使用DataContractSerializer。与XmlSerializer相比,它可以处理对同一对象的多个引用,以使数据不会在xml中重复,并且可以像保存的那样还原。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接