刚刚接触linq to xml,想向现有的xml文件继续写入数据,而不是覆盖,应该如何解决。没有找到类似Append之类的方法。希望有人指点一下xmllinqc#

解决方案 »

  1.   

            /// <summary>
            /// 2、添加元素
            /// </summary>
            /// <param name="xmlpath">XML文件的路径</param>
            private static void AddXmlElement(string xmlpath)
            {
                ///导入XML文件
                XElement xe = XElement.Load(xmlpath);
                ///创建一个新节点
                XElement book1 = new XElement("Book",
                                   new XAttribute("BookID", "002"),
                                   new XElement("BookNo", "0002"),
                                   new XElement("BookName", "Book 0002"),
                                   new XElement("BookPrice", "50"),
                                   new XElement("BookRe", "This is a book 0002")
                    );
                ///添加节点到XML文件中,并保存
                xe.Add(book1);
                ///创建一个新节点
                XElement book2 = new XElement("Book",
                                   new XAttribute("BookID", "003"),
                                   new XElement("BookNo", "0003"),
                                   new XElement("BookName", "Book 0003"),
                                   new XElement("BookPrice", "30"),
                                   new XElement("BookRe", "This is a book 0003")
                    );
                ///添加节点到XML文件中,并保存
                xe.Add(book2);
                ///创建一个新节点
                XElement book3 = new XElement("Book",
                                   new XAttribute("BookID", "004"),
                                   new XElement("BookNo", "0004"),
                                   new XElement("BookName", "Book 0004"),
                                   new XElement("BookPrice", "60"),
                                   new XElement("BookRe", "This is a book 0004")
                    );
                ///添加节点到XML文件中
                xe.Add(book3);
                ///保存到XML文件中
                xe.Save(xmlpath);            Console.WriteLine(xe);
            }
                //调用函数AddXmlElement(string xmlpath)
                ///添加XML元素
                Program.AddXmlElement(@"C:\BookStore.xml");参考博客http://bbs.csdn.net/topics/390017085