.NET中的XML数据管理

我在.NET中学习Xml数据处理。 我有以下XML格式。

  book 1 author 1 10.90 1985   book 2 author 2 20.90 1995   

我需要学习添加/编辑/删除新书到XML文件。 能否请您指导我们探索这些function的所有课程。 我发现许多类如XmlDocument XmlTextWriter等。一些网站建议也使用LINQ。 我很困惑哪个去了。 有什么好的材料我可以参考了解这一点。

以下是使用LINQ to XML添加和删除元素的示例:

 // load the XML file into an XElement XElement xml = XElement.Load(filePath); // add a new book xml.Add( new XElement("BOOK", new XElement("TITLE", "book 3"), new XElement("AUTHOR", "author 3"), new XElement("PRICE", 0.1), new XElement("YEAR", 2012))); // remove a book that matches the desired title xml.Elements("BOOK").Where(x => x.Element("TITLE").Value == "book 1").Remove(); // to edit an existing element: xml.Elements("BOOK") .Single(x => x.Element("TITLE").Value == "book 2") // take a single book .Element("AUTHOR").Value = "new author"; // and change its author field 

基本上,只要你对这项技术感到满意,就可以使用你想要的任何东西。 在我看来,LINQ to SQL似乎更容易一些。

如果文件很小 – 即大小不是几MB – 你应该使用XmlDocument (经典方式)或XDocument (用于XML处理的新LINQ类)。 你会发现很多两个例子。
以下搜索结果可能会提示您何时应使用以下哪些类: http : //www.google.com/search?hl = en&q = XmlDocument%20vs .% 20XDocument 。 就个人而言,我建议使用XDocument ,因为它的API更容易使用。