以下是代码。我的问题是,如果我想创建这个文件,那么稍后使用XmlWriter
重新打开它并向当前文件添加更多内容如何做到这一点?喜欢使用XmlWriter
using System.Xml;
class Program
{
class Employee
{
int _id;
string _firstName;
string _lastName;
int _salary;
public Employee(int id, string firstName, string lastName, int salary)
{
this._id = id;
this._firstName = firstName;
this._lastName = lastName;
this._salary = salary;
}
public int Id { get { return _id; } }
public string FirstName { get { return _firstName; } }
public string LastName { get { return _lastName; } }
public int Salary { get { return _salary; } }
}
static void Main()
{
Employee[] employees = new Employee[4];
employees[0] = new Employee(1, "David", "Smith", 10000);
employees[1] = new Employee(3, "Mark", "Drinkwater", 30000);
employees[2] = new Employee(4, "Norah", "Miller", 20000);
employees[3] = new Employee(12, "Cecil", "Walker", 120000);
using (XmlWriter writer = XmlWriter.Create("employees.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("Employees");
foreach (Employee employee in employees)
{
writer.WriteStartElement("Employee");
writer.WriteElementString("ID", employee.Id.ToString());
writer.WriteElementString("FirstName", employee.FirstName);
writer.WriteElementString("LastName", employee.LastName);
writer.WriteElementString("Salary", employee.Salary.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
}
答案 0 :(得分:0)
我会重构Employee
类并为序列化创建一个Employees
类,如下所示:
[XmlRoot("Employees")]
public class Employees : List<Employee> { }
public class Employee
{
int _id;
string _firstName;
string _lastName;
int _salary;
public Employee() { }
public Employee(int id, string firstName, string lastName, int salary)
{
this._id = id;
this._firstName = firstName;
this._lastName = lastName;
this._salary = salary;
}
[XmlElement("ID")]
public int Id
{
get { return _id; }
set { _id = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public int Salary
{
get { return _salary; }
set { _salary = value; }
}
}
现在你可以轻松地做你想做的事了:
Employees employees = new Employees();
employees.Add(new Employee(1, "David", "Smith", 10000));
employees.Add(new Employee(3, "Mark", "Drinkwater", 30000));
employees.Add(new Employee(4, "Norah", "Miller", 20000));
employees.Add(new Employee(12, "Cecil", "Walker", 120000));
XmlSerializer ser = new XmlSerializer(typeof(Employees));
ser.Serialize(Console.OpenStandardOutput(), employees);
Console.ReadKey();
并将其取回
XmlSerializer ser = new XmlSerializer(typeof(Employees));
Employees emps = (Employees)ser.Deserialize(File.OpenRead("employees.xml"));
emps.Add(new Employeee...);
ser.Serialize(File.OpenWrite("employees.xml"), emps);
随着对象的增长,使用新属性装饰成员要容易得多,而不是重写涉及XmlReader
/ XmlWriter
代码。