繁体   English   中英

我想保存现有的List <T> 到c#中的XML文件

[英]I want to save an existing List<T> into an XML file in c#

我有一个地方类定义如下:

    public class place
    {
            public string placeID { get; set; }
            public string placeCatID { get; set; }
            public string placeName { get; set; }
    }

并且数据存储在列表调用placelist中

    List<place> placelist = new List<place>();

可以指导我如何将placelist转换为字符串或导出它并将其保存为XML文件格式,如下所示:

    <place>
            <pID>0001</pID>
            <pCatID>C1</pID>
            <pName>Location 1</pName>
    </place>
    <place>
            <pID>0002</pID>
            <pCatID>C1</pID>
            <pName>Location 2</pName>
    </place>

语言使用是C#

谢谢。

您可以使用任何序列化为XML的序列化程序。 我建议使用DataContractSerializer

来自MSDN:

DataContractSerializer s = new DataContractSerializer(typeof(T));
    using (FileStream fs = File.Open("test" + typeof(T).Name + ".xml", FileMode.Create))
    {
        Console.WriteLine("Testing for type: {0}", typeof(T)); 
        s.WriteObject(fs, obj);
    }

http://msdn.microsoft.com/en-us/library/bb675198.aspx

在您的情况下,用List<T>替换T.

简而言之,可以使用以下选项:

下面的解决方案适用于XmlSerializer但您也可以使用DataContractSerializer XmlSerializer默认序列化所有字段,使用DataContractSerializer您需要明确指定要序列化的内容。

添加序列化属性以具有自定义元素名称:

public class place
{
    [XmlElement("pID")]
    public string placeID { get; set; }
    [XmlElement("pCatID")]
    public string placeCatID { get; set; }
    [XmlElement("pName")]
    public string placeName { get; set; }
}

序列化代码:

var ser = new XmlSerializer(typeof(List<place>));
TextWriter writer = new StreamWriter(@"C:\1.xml");
// o is List<place> here
ser.Serialize(writer, o);

XML:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfPlace xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <place>
    <pID>1</pID>
    <pCatID>2</pCatID>
    <pName>3</pName>
  </place>
  <place>
    <pID>3</pID>
    <pCatID>4</pCatID>
    <pName>5</pName>
  </place>
</ArrayOfPlace>

您可以编写自己的ToXml()方法或使用DataContractSerializer

我刚写了一篇关于将对象数据保存到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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM