C#基础知识---Linq操作XML文件
概述
Linq也就是Language Integrated Query的缩写,即语言集成查询,是微软在.Net 3.5中提出的一项新技术。
Linq主要包含4个组件---Linq to Objects、Linq to XML、Linq to DataSet 和Linq to SQL。
- Linq to SQL 组件——可以查询基于关系数据的数据
- Linq to Dataset组件——可以查询DasaSet对象中的数据,并对数据进行增删改查的操作
- Linq to Objects组件——可以查询IEnumberable 或IEnumberable<T>集合
- Linq to XML 组件——可以查询和操作XML文件,比Xpath操作XML更加方便
一、使用Linq创建XML文件
1 public static class XMLFileHelper 2 { 3 /// <summary> 4 /// Create a xml file 5 /// </summary> 6 /// <param name="xmlPath"></param> 7 private static void CreateXmlFile(string xmlPath) 8 { 9 try 10 { 11 //定义一个XDocument结构 12 object[] content = new object[20]; 13 content[0] = new XElement("User", new XAttribute("Id", "1"), 14 new XElement("Name", "Jack"), 15 new XElement("Password", "123456"), 16 new XElement("Description", "I am Jack") 17 ); 18 content[1] = new XElement("User", new XAttribute("Id", "2"), 19 new XElement("Name", "Mary"), 20 new XElement("Password", "135678"), 21 new XElement("Description", "I am Mary") 22 ); 23 content[2] = new XAttribute("Id", "root"); 24 25 content[3] = new XElement("User", new XAttribute("Id", "3"), 26 new XElement("Name", "Tom"), 27 new XElement("Password", "654123"), 28 new XElement("Description", "I am Tom") 29 ); 30 31 XDocument myXDoc = new XDocument(new XElement("Users", content)); 32 myXDoc.Save(xmlPath); 33 } 34 catch (Exception ex) 35 { 36 Console.WriteLine(ex.ToString()); 37 } 38 } 39 }
创建后的xml文件如下所示:
二、使用Linq读取Xml文件
1 public static void GetXmlNodeInformation(string xmlPath) 2 { 3 try 4 { 5 //定义并从xml文件中加载节点(根节点) 6 XElement rootNode = XElement.Load(xmlPath); 7 //查询语句: 获得根节点下name子节点(此时的子节点可以跨层次:孙节点、重孙节点......) 8 IEnumerable<XElement> targetNodes = from target in rootNode.Descendants("Name") 9 where target.Value.Contains("a") 10 select target; 11 foreach (XElement node in targetNodes) 12 { 13 Console.WriteLine("Name = {0}", node.Value); 14 } 15 Console.WriteLine(); 16 IEnumerable<XElement> myTargetNodes = from myTarget in rootNode.Descendants("User") 17 where myTarget.HasElements 18 select myTarget; 19 foreach (XElement node in myTargetNodes) 20 { 21 Console.WriteLine("Name = {0}", node.Element("Name").Value); 22 Console.WriteLine("Password = {0}", node.Element("Password").Value); 23 Console.WriteLine("Description = {0}", node.Element("Description").Value); 24 Console.WriteLine(); 25 } 26 } 27 catch (Exception ex) 28 { 29 Console.WriteLine(ex.ToString()); 30 } 31 }