LINQ XML的基本操作

来源:互联网 发布:路由器连接上没有网络 编辑:程序博客网 时间:2024/06/05 08:03

                 这几天想写点基础的博客内容,正好最近在用XML,就写了一点XML的基本操作。

 通过函数的形式表现出来。

         /*             -------------------------------------                Context:LINQ TO  XML             -------------------------------------                 Author:Chinajiyong             -------------------------------------                 DateTime:2012-04-21            -------------------------------------                 通过函数的形式表现出来            -------------------------------------          */
        /// <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")                );            ///添加节点到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("BookRemark", "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("BookRemark", "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");
运行结果:


        /// <summary>        ///  3、修改XML文件的元素        /// </summary>        /// <param name="xmlpath">XML文件的路径</param>        /// <param name="strElement">指定的修改元素</param>        private static void ModifyXmlElement(string xmlpath, string strElement)        {            XElement xe = XElement.Load(xmlpath);            ///查询修改的元素            IEnumerable<XElement> element = from e in xe.Elements("Book")                                            where e.Attribute("BookID").Value == strElement                                            select e;            ///修改元素            if (element.Count() > 0)            {                XElement firstelement = element.First();                ///设置新的属性                firstelement.SetAttributeValue("BookID", "new004");                ///替换成新的节点                firstelement.ReplaceNodes(                        new XElement("BookNo", "new0004"),                        new XElement("BookName", "Book new0004"),                        new XElement("BookPrice", "45"),                        new XElement("BookRemark", "This is a book new0004")                    );            }            xe.Save(xmlpath);            Console.WriteLine(xe);        }
调用函数ModifyXmlElement(string xmlpath, string strElement)

            ///修改XML文件的元素            Program.ModifyXmlElement(@"C:\BookStore.xml", "004");

运行结果:

        /// <summary>        /// 4、删除XML文件的元素        /// </summary>        /// <param name="xmlpath">XML文件的路径</param>        /// <param name="strElement">指定删除元素</param>        private static void DeleteXmlElement(string xmlpath, string strElement)        {            XElement xe = XElement.Load(xmlpath);            ///查询修改的元素            IEnumerable<XElement> element = from e in xe.Elements("Book")                                            where e.Attribute("BookID").Value == strElement                                            select e;            ///修改元素            if (element.Count() > 0)            {                XElement firstelement = element.First();                ///删除此元素的所有节点和属性                firstelement.RemoveAll();                ///删除此元素的属性                //firstelement.RemoveAttributes();                ///删除此元素的子节点                //firstelement.RemoveNodes();            }            xe.Save(xmlpath);            Console.WriteLine(xe);        }
调用函数 DeleteXmlElement(string xmlpath, string strElement)
            ///删除XML元素            Program.DeleteXmlElement(@"C:\BookStore.xml","new004");
运行结果:


        /// <summary>        /// 5、将XML文件中的属性更换成元素        /// </summary>        /// <param name="xmlpath">XML文件的路径</param>        /// <param name="strAttribute">指定要更换的属性</param>        private static void ConvertAttributeToElement(string xmlpath, string strAttribute)        {            XElement xe = XElement.Load(xmlpath);            ///查询更换的元素            IEnumerable<XElement> element = from e in xe.Elements("Book")                                            where e.Attribute("BookID").Value == strAttribute                                            select e;            ///更换为元素            if (element.Count() > 0)            {                XElement firstelement = element.First();                //获取第一个属性                XAttribute attr = firstelement.FirstAttribute;                //XAttribute attr = firstelement.Attribute("BookID");                ///将属性转换成元素                firstelement.AddFirst(                    new XElement(attr.Name, attr.Value)//添加BookID元素                    );                ///删除属性                firstelement.RemoveAttributes();            }            xe.Save(xmlpath);            Console.WriteLine(xe);        }
调用函数:ConvertAttributeToElement(string xmlpath, string strAttribute)
            ///删除XML元素            //Program.DeleteXmlElement(@"C:\BookStore.xml","new004");//注释这一样            ///将文件中的属性更换成元素            Program.ConvertAttributeToElement(@"C:\BookStore.xml","new004");

运行结果:


        /// <summary>        /// 6、查询根元素        /// </summary>        /// <param name="xmlpath">XML文件的路径</param>        private static void QueryRootElement(string xmlpath)        {            XDocument doc = XDocument.Load(xmlpath);            Console.WriteLine(doc.Root.Name);            //IEnumerable<XElement> RootElement = from root in doc.Elements("Books")            //                                    select root;            /////输出根元素            //foreach (XElement xe in RootElement)            //{            //    Console.WriteLine(xe.Name);            //}        }
调用函数:QueryRootElement(string xmlpath)
            /// 查询根元素            Program.QueryRootElement(@"C:\BookStore.xml");
运行结果:

Books
        /// <summary>        /// 7、查询指定名称的元素        /// </summary>        /// <param name="xmlpath">XML文件的路径</param>        /// <param name="strName">查询元素名称</param>        private static void QueryElementByName(string xmlpath, string strName)        {            XElement xe = XElement.Load(xmlpath);            ///查询元素            var elements = xe.Elements("Book")                         .Where(e => (string)e.Element("BookName") == strName)                         .OrderBy(e => e.Element("BookName"))                         .ToList();            elements.ForEach(e => Console.WriteLine(e));        }
调用函数:QueryElementByName(string xmlpath, string strName)

            ///查询指定名称的元素            Program.QueryElementByName(@"C:\BookStore.xml", "Book 0003");
运行结果:



        /// <summary>        /// 8、查询指定属性的元素        /// </summary>        /// <param name="xmlpath">XML文件的路径</param>        /// <param name="strName">指定的属性</param>        private static void QueryElementByAttribute(string xmlpath, string strAttribute)        {            XElement xe = XElement.Load(xmlpath);            ///查询元素            var eAttribute = xe.Elements("Book")                         .Where(e => (string)e.Attribute("BookID") == strAttribute)                         .OrderBy(e => e.Element("BookID"))                         .ToList();            eAttribute.ForEach(e => Console.WriteLine(e));        }
调用函数:QueryElementByAttribute(string xmlpath, string strAttribute)
            ///查询指定属性的元素            Program.QueryElementByAttribute(@"C:\BookStore.xml", "003");
运行结果:


        /// <summary>        /// 9、查询指定元素的子元素        /// </summary>        /// <param name="xmlpath">XML文件的路径</param>        /// <param name="strSubElement">指定元素</param>        private static void QuerySubElement(string xmlpath, string strSubElement)        {            XElement xe = XElement.Load(xmlpath);            var elements = xe.Elements("Book")                         .Descendants("BookRemark")                         .ToList();            foreach (var e in elements)            {                Console.WriteLine(e.Name.LocalName + "\t" + e.Value);            }        }
调用函数:QuerySubElement(string xmlpath, string strSubElement)

            ///查询指定元素的子元素            Program.QuerySubElement(@"C:\BookStore.xml", "BookRemark");
运行结果:

        /// <summary>        /// 10、查询元素并排序        /// </summary>        /// <param name="xmlpath">XML文件的路径</param>        private static void QueryElementByOrder(string xmlpath)        {            XElement xe = XElement.Load(xmlpath);            var elements = xe.Elements("Book")                         .Where(e => Convert.ToInt32(e.Attribute("BookID").Value.Substring(e.Attribute("BookID").Value.Length - 1, 1)) > 1)                         .OrderByDescending(e => (string)e.Element("BookName"))                         .ToList();            elements.ForEach(e => Console.WriteLine(e.Element("BookName").Value));        }
调用函数:QueryElementByOrder(string xmlpath)
            /// 查询元素并排序            Program.QueryElementByOrder(@"C:\BookStore.xml");
运行结果:


        /// <summary>        /// 11、查询元素并计算Price平均值        /// </summary>        /// <param name="xmlpath">XML文件的路径</param>        private static void QueryElementByCoeompute(string xmlpath)        {            XElement xe = XElement.Load(xmlpath);            var elements = xe.Elements("Book")                            .Where(e => Convert.ToInt32(e.Attribute("BookID").Value.Substring(e.Attribute("BookID").Value.Length - 1, 1)) > 1)                         .OrderByDescending(e => (string)e.Element("BookName"))                         .ToList();            Console.WriteLine("Average:" + elements.Average(e => Convert.ToInt32(e.Element("BookPrice").Value)));        }
调用函数:QueryElementByCoeompute(string xmlpath)
            /// 查询元素并计算Price平均值            Program.QueryElementByCoeompute(@"C:\BookStore.xml");
运行结果:



到此为止全部操作已经完成。整个操作仍然很简单。

原创粉丝点击