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();
            }
        }
    }
4

4 回答 4

46

序列化对象有更简单的方法,请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);
}
于 2012-11-07T09:16:58.710 回答
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>();
于 2012-11-07T09:21:05.413 回答
1

我刚刚写了一篇关于将对象数据保存为 Binary、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");
于 2014-03-15T00:03:54.613 回答
0

对于我的项目,我使用DataContractSerializer。我与XmlSerializer相比,它可以处理对同一对象的多个引用,这样数据不会在 xml 中重复并恢复为已保存。

于 2012-11-07T09:22:41.720 回答