我正在寻找一种方法来将一个元素添加到我通过序列化List构建的xml文档中 客户
CUSTOMER:
public class Customer
{
[XmlElement("CustomerId")]
public Guid CustomerId { get; set; }
[XmlElement("FirstName")]
public string FirstName { get; set; }
[XmlElement("LastName")]
public string LastName { get; set; }
[XmlElement("DOB")]
public DateTime DOB { get; set; }
}
CUSTOMERS列表(创建xml时为空)
private void CreateXml(string path)
{
File.Create(path).Close();
List<Customer> customers = new List<Customer>();
XmlSerializer serializer = new XmlSerializer(typeof(List<Customer>));
TextWriter textWriter = new StreamWriter(path);
serializer.Serialize(textWriter, customers);
textWriter.Close();
}
我现在如何向xml文件中添加一个新的Customer元素,而不必编写分配 DOM样式代码?
编辑:
我找到了一个解决方法:
我让客户到客户列表并将整个列表重新序列化为xml文档
public void AddCustomer(Customer customer)
{
TextWriter textWriter = new StreamWriter(XMLRepository.CustomersPath);
customers.Add(customer);
serializer.Serialize(textWriter, customers);
textWriter.Close();
}
这是一个很好的方法,任何人都可以想到更好的方法吗? (我猜是的)..