c#以xml格式存储数据 - 如何读取和写入数据

时间:2015-02-01 12:13:31

标签: c# xml serialization

我正在创建一个程序,用于在rota / schedule中分配轮班,直到现在我一直在使用包含其中人员记录的硬编码类。

我现在正在寻找正确存储数据的方法,并且认为xml可能是一种很好的方法。

我有一个类Person,其中包含人员的信息和一个类MyDataSource,它创建了Person类的5个实例,并将它们存储在我可以添加的列表中或移到。

我一直在寻找使用灭菌来读取和写入xml文件,但我很难理解它。

我是否可以将代码添加到现有的Person类中,还是需要创建一个单独的类来执行此操作?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;


namespace ShiftSorter
{
    public class Person
    {
        public string name { get; set; }
        public int hours { get; set; }
        public int row { get; set; }
        public string unit { get; set; }

        /// <summary>
        /// Creates a new instance of the object Person.
        /// </summary>
        /// <param name="newName">The name of the person</param>
        public Person(string newName)
        {
            name = newName;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

首先,您的类应该是Serializable:

using System.Xml.Serialization;

[Serializable]
public class Person { }

其次,您需要创建空构造函数,仅用于XML解析:

// Default constructor for serialization
public Person() { }

从现在起,每个公共字段都将按方法序列化 - 反序列化:

private void Serialize()
{
    using (FileStream fs = new FileStream("person.xml", FileMode.Create))
    {
        XmlSerializer serializer = new XMLSerializer(typeof(Person));
        serializer.Serialize(fs, this);
    }
}

public static Person Deserialize(string filename = "person.xml")
{
    using (FileStream fs = new FileStream(filename, FileMode.Open))
    {
        XmlSerializer serializer = new XMLSerializer(typeof(Person));
        return (Person)serializer.Deserialize(fs);
    }
}

您可以通过以下方式从文件创建类

Person person = Person.Deserialize("person.xml");
相关问题