我刚刚写了一篇关于将对象数据保存为 Binary、XML 或 Json 的博文。因为您希望类变量在 xml 文件中的名称与它们在代码中的名称不同,所以您需要使用 [XmlElement("NameToShowUpInXmlFileGoesHere")] 来装饰每个公共属性。
一旦你有了它,只需调用以下函数来保存对象实例并将其加载到文件中/从文件中加载。
注意:这需要将 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();
}
}
例子
public class place
{
[XmlElement("pID")]
public string placeID { get; set; }
[XmlElement("pCatID")]
public string placeCatID { get; set; }
[XmlElement("pName")]
public string placeName { get; set; }
}
// To write the placeList variable contents to XML.
WriteToXmlFile<List<place>>("C:\places.txt", placeList);
// To read the xml file contents back into a variable.
List<place> placeList= ReadFromXmlFile<List<place>>("C:\places.txt");