转自: http://blog.csdn.net/chinajiyong/article/details/7485019
这几天想写点基础的博客内容,正好最近在用XML,就写了一点XML的基本操作。
通过函数的形式表现出来。
- /*
- -------------------------------------
- Context:LINQTOXML
- -------------------------------------
- Author:Chinajiyong
- -------------------------------------
- DateTime:2012-04-21
- -------------------------------------
- 通过函数的形式表现出来
- -------------------------------------
- */
- ///<paramname="xmlpath">XML文件的路径</param>
- privatestaticvoidCreateXmlFile(stringxmlpath)
- {
- XDocumentdoc=newXDocument(///创建XDocument类的实例
- newXDeclaration("1.0","utf-8","yes"),///XML的声明,包括版本,编码,xml文件是否独立
- newXElement("Books",///添加根节点
- newXElement("Book",///添加一个节点
- newXAttribute("BookID","001"),///添加属性BookID
- newXElement("BookNo","0001"),///添加元素BookNo
- newXElement("BookName","Book0001"),///添加元素BookName
- newXElement("BookPrice","40"),///添加元素BookPrice
- newXElement("BookRemark","Thisisabook0001")///添加元素BookRemark
- )
- )
- );
- ///保存XML文件到指定地址
- doc.Save(xmlpath);
- Console.WriteLine(doc);
- }
- staticvoidMain(string[]args)
- {
- ///创建一个名为BookStore.xml的xml文件
- Program.CreateXmlFile(@"C:\BookStore.xml");
- }
运行结果:
- ///<summary>
- ///2、添加元素
- ///</summary>
- ///<paramname="xmlpath">XML文件的路径</param>
- privatestaticvoidAddXmlElement(stringxmlpath)
- {
- ///导入XML文件
- XElementxe=XElement.Load(xmlpath);
- ///创建一个新节点
- XElementbook1=newXElement("Book",
- newXAttribute("BookID","002"),
- newXElement("BookNo","0002"),
- newXElement("BookName","Book0002"),
- newXElement("BookPrice","50"),
- newXElement("BookRemark","Thisisabook0002")
- );
- ///添加节点到XML文件中,并保存
- xe.Add(book1);
- ///创建一个新节点
- XElementbook2=newXElement("Book","003"),"0003"),"Book0003"),"30"),"Thisisabook0003")
- );
- ///添加节点到XML文件中,并保存
- xe.Add(book2);
- ///创建一个新节点
- XElementbook3=newXElement("Book","004"),"0004"),"Book0004"),"60"),"Thisisabook0004")
- );
- ///添加节点到XML文件中
- xe.Add(book3);
- ///保存到XML文件中
- xe.Save(xmlpath);
- Console.WriteLine(xe);
- }
- ///添加XML元素
- Program.AddXmlElement(@"C:\BookStore.xml");
- ///<summary>
- ///3、修改XML文件的元素
- ///</summary>
- ///<paramname="xmlpath">XML文件的路径</param>
- ///<paramname="strElement">指定的修改元素</param>
- privatestaticvoidModifyXmlElement(stringxmlpath,stringstrElement)
- {
- XElementxe=XElement.Load(xmlpath);
- ///查询修改的元素
- IEnumerable<XElement>element=fromeinxe.Elements("Book")
- wheree.Attribute("BookID").Value==strElement
- selecte;
- ///修改元素
- if(element.Count()>0)
- {
- XElementfirstelement=element.First();
- ///设置新的属性
- firstelement.SetAttributeValue("BookID","new004");
- ///替换成新的节点
- firstelement.ReplaceNodes(
- newXElement("BookNo","new0004"),
- newXElement("BookName","Booknew0004"),
- newXElement("BookPrice","45"),
- newXElement("BookRemark","Thisisabooknew0004")
- );
- }
- xe.Save(xmlpath);
- Console.WriteLine(xe);
- }
运行结果:
- ///<summary>
- ///4、删除XML文件的元素
- ///</summary>
- ///<paramname="xmlpath">XML文件的路径</param>
- ///<paramname="strElement">指定删除元素</param>
- privatestaticvoidDeleteXmlElement(stringxmlpath,stringstrElement)
- {
- XElementxe=XElement.Load(xmlpath);
- ///查询修改的元素
- IEnumerable<XElement>element=fromeinxe.Elements("Book")
- wheree.Attribute("BookID").Value==strElement
- selecte;
- ///修改元素
- if(element.Count()>0)
- {
- XElementfirstelement=element.First();
- ///删除此元素的所有节点和属性
- firstelement.RemoveAll();
- ///删除此元素的属性
- //firstelement.RemoveAttributes();
- ///删除此元素的子节点
- //firstelement.RemoveNodes();
- }
- xe.Save(xmlpath);
- Console.WriteLine(xe);
- }
- ///删除XML元素
- Program.DeleteXmlElement(@"C:\BookStore.xml","new004");
- ///<summary>
- ///5、将XML文件中的属性更换成元素
- ///</summary>
- ///<paramname="xmlpath">XML文件的路径</param>
- ///<paramname="strAttribute">指定要更换的属性</param>
- privatestaticvoidConvertAttributeToElement(stringxmlpath,stringstrAttribute)
- {
- XElementxe=XElement.Load(xmlpath);
- ///查询更换的元素
- IEnumerable<XElement>element=fromeinxe.Elements("Book")
- wheree.Attribute("BookID").Value==strAttribute
- selecte;
- ///更换为元素
- if(element.Count()>0)
- {
- XElementfirstelement=element.First();
- //获取第一个属性
- XAttributeattr=firstelement.FirstAttribute;
- //XAttributeattr=firstelement.Attribute("BookID");
- ///将属性转换成元素
- firstelement.AddFirst(
- newXElement(attr.Name,attr.Value)//添加BookID元素
- );
- ///删除属性
- firstelement.RemoveAttributes();
- }
- xe.Save(xmlpath);
- Console.WriteLine(xe);
- }
运行结果:
- ///<summary>
- ///6、查询根元素
- ///</summary>
- ///<paramname="xmlpath">XML文件的路径</param>
- privatestaticvoidQueryRootElement(stringxmlpath)
- {
- XDocumentdoc=XDocument.Load(xmlpath);
- Console.WriteLine(doc.Root.Name);
- //IEnumerable<XElement>RootElement=fromrootindoc.Elements("Books")
- //selectroot;
- /////输出根元素
- //foreach(XElementxeinRootElement)
- //{
- //Console.WriteLine(xe.Name);
- //}
- }
- <prename="code"class="csharp">///查询根元素
- Program.QueryRootElement(@"C:\BookStore.xml");</pre><strong><spanstyle="font-size:18px">运行结果:</span></strong><p></p>
- <pre></pre>
- <prename="code"class="csharp"style="background-color:rgb(255,255,255);">Books</pre><prename="code"class="csharp">///<summary>
- ///7、查询指定名称的元素
- ///</summary>
- ///<paramname="xmlpath">XML文件的路径</param>
- ///<paramname="strName">查询元素名称</param>
- privatestaticvoidQueryElementByName(stringxmlpath,stringstrName)
- {
- XElementxe=XElement.Load(xmlpath);
- ///查询元素
- varelements=xe.Elements("Book")
- .Where(e=>(string)e.Element("BookName")==strName)
- .OrderBy(e=>e.Element("BookName"))
- .ToList();
- elements.ForEach(e=>Console.WriteLine(e));
- }</pre><strong><spanstyle="font-size:18px">调用函数:QueryElementByName(stringxmlpath,stringstrName)</span></strong><br>
- <br>
- <prename="code"class="csharp">///查询指定名称的元素
- Program.QueryElementByName(@"C:\BookStore.xml","Book0003");</pre><strong><spanstyle="font-size:18px">运行结果:</span></strong>
- <p></p>
- <p><imgsrc="http://my.csdn.net/uploads/201204/21/1335011713_3231.png"alt=""><br>
- <br>
- </p><prename="code"class="csharp">///<summary>
- ///8、查询指定属性的元素
- ///</summary>
- ///<paramname="xmlpath">XML文件的路径</param>
- ///<paramname="strName">指定的属性</param>
- privatestaticvoidQueryElementByAttribute(stringxmlpath,stringstrAttribute)
- {
- XElementxe=XElement.Load(xmlpath);
- ///查询元素
- vareAttribute=xe.Elements("Book")
- .Where(e=>(string)e.Attribute("BookID")==strAttribute)
- .OrderBy(e=>e.Element("BookID"))
- .ToList();
- eAttribute.ForEach(e=>Console.WriteLine(e));
- }</pre><strong><spanstyle="font-size:18px">调用函数:QueryElementByAttribute(stringxmlpath,stringstrAttribute)</span></strong><br>
- <prename="code"class="csharp">///查询指定属性的元素
- Program.QueryElementByAttribute(@"C:\BookStore.xml","003");</pre><spanstyle="font-size:18px"><strong>运行结果:</strong></span><p></p>
- <p><imgsrc="http://my.csdn.net/uploads/201204/21/1335011840_7341.png"alt=""><br>
- </p><prename="code"class="csharp">///<summary>
- ///9、查询指定元素的子元素
- ///</summary>
- ///<paramname="xmlpath">XML文件的路径</param>
- ///<paramname="strSubElement">指定元素</param>
- privatestaticvoidQuerySubElement(stringxmlpath,stringstrSubElement)
- {
- XElementxe=XElement.Load(xmlpath);
- varelements=xe.Elements("Book")
- .Descendants("BookRemark")
- .ToList();
- foreach(vareinelements)
- {
- Console.WriteLine(e.Name.LocalName+"\t"+e.Value);
- }
- }</pre><strong><spanstyle="font-size:18px">调用函数:QuerySubElement(stringxmlpath,stringstrSubElement)</span></strong><p></p>
- <p></p><prename="code"class="csharp">///查询指定元素的子元素
- Program.QuerySubElement(@"C:\BookStore.xml","BookRemark");</pre><spanstyle="font-size:18px"><strong>运行结果:</strong></span><p></p>
- <p><imgsrc="http://my.csdn.net/uploads/201204/21/1335011970_6889.png"alt=""></p>
- <p></p><prename="code"class="csharp">///<summary>
- ///10、查询元素并排序
- ///</summary>
- ///<paramname="xmlpath">XML文件的路径</param>
- privatestaticvoidQueryElementByOrder(stringxmlpath)
- {
- XElementxe=XElement.Load(xmlpath);
- varelements=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));
- }</pre><strong><spanstyle="font-size:18px">调用函数:QueryElementByOrder(stringxmlpath)</span></strong><br>
- <prename="code"class="csharp">///查询元素并排序
- Program.QueryElementByOrder(@"C:\BookStore.xml");</pre><spanstyle="font-size:18px"><strong>运行结果:</strong></span><p></p>
- <p><imgsrc="http://my.csdn.net/uploads/201204/21/1335012340_2136.png"alt=""><br>
- </p><prename="code"class="csharp">///<summary>
- ///11、查询元素并计算Price平均值
- ///</summary>
- ///<paramname="xmlpath">XML文件的路径</param>
- privatestaticvoidQueryElementByCoeompute(stringxmlpath)
- {
- XElementxe=XElement.Load(xmlpath);
- varelements=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)));
- }</pre><strong><spanstyle="font-size:18px">调用函数:QueryElementByCoeompute(stringxmlpath)</span></strong><br>
- <prename="code"class="csharp">///查询元素并计算Price平均值
- Program.QueryElementByCoeompute(@"C:\BookStore.xml");</pre><strong><spanstyle="font-size:18px">运行结果:</span></strong><p></p>
- <p><imgsrc="http://my.csdn.net/uploads/201204/21/1335012463_5700.png"alt=""><br>
- <br>
- </p>
- <p><spanstyle="font-size:18px">到此为止全部操作已经完成。整个操作仍然很简单。</span></p>