日期:2014-05-20  浏览次数:20775 次

------------LINQ操作XML--------------
RT,LINQ操作XML,目的和上篇一样。不解释!!

        /// <summary>
        /// 1、创建BookStore.xml的XML文件,由函数CreateXmlFile()完成
        /// </summary>
        /// <param name="xmlpath">XML文件的路径</param>
        private static void CreateXmlFile(string xmlpath)
        {
            XDocument doc = new XDocument(              ///创建XDocument类的实例
                new XDeclaration("1.0", "utf-8", "yes"),///XML的声明,包括版本,编码,xml文件是否独立
                new XElement("Books",                   ///添加根节点
                    new XElement("Book",                ///添加一个节点
                        new XAttribute("BookID", "001"),///添加属性BookID
                        new XElement("BookNo", "0001"), ///添加元素BookNo
                        new XElement("BookName", "Book 0001"),///添加元素BookName
                        new XElement("BookPrice", "40"),///添加元素BookPrice
                        new XElement("BookRemark", "This is a book 0001")///添加元素BookRemark
                                 )
                             )
                );
            ///保存XML文件到指定地址
            doc.Save(xmlpath);
            Console.WriteLine(doc);
        }
      //调用函数CreateXmlFile(string xmlpath)
      static void Main(string[] args)
        {
            ///创建一个名为BookStore.xml的xml文件
            Program.CreateXmlFile(@"C:\BookStore.xml");
         }
     


        /// <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("BookRemark", "This is a book 0002")