我想将数据添加到现有的xml文件中,而不必将现有文件加载到momory中。
我有一个数据模型:
public class clsPerson
{
public string FirstName;
public string LastName;
public List<string> Likes;
}
我有这个代码,将两个人添加到xml文件,关闭文件,然后我想再添加两个人......
static void Main(string[] args)
{
List<clsPerson> p1 = new List<clsPerson>();
p1.Add(new clsPerson { FirstName = "John", LastName = "Dow", Likes = new List<string> { "Apples", "Bananas" } });
p1.Add(new clsPerson { FirstName = "Jane", LastName = "Dow", Likes = new List<string> { "Football", "Tennis" } });
string file = @"D:\people.xml";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p1.GetType());
TextWriter tw = new StreamWriter(file);
x.Serialize(tw, p1);
tw.Close();
List<clsPerson> p2 = new List<clsPerson>();
p2.Add(new clsPerson { FirstName = "New", LastName = "Guy", Likes = new List<string> { "Reading", "Walking" } });
p2.Add(new clsPerson { FirstName = "Another", LastName = "Girl", Likes = new List<string> { "Surfing", "Running" } });
//... i want to add p2 to people.xml without having to load the entire file into memory again
}
我可以通过重新加载文件来添加两个新条目,将所有节点读入列表并添加新条目,但这似乎效率低下,特别是如果xml中有1000个条目。