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组件——可以查询IEnumberableIEnumberable<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         }
View Code

创建后的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             }
View Code

运行结果如下:

三、使用Linq修改Xml文件

 1   public static void ModifyXmlNodeInformation(string xmlPath)
 2             {
 3                 try
 4                 {
 5                     //定义并从xml文件中加载节点(根节点)
 6                     XElement rootNode = XElement.Load(xmlPath);
 7                     IEnumerable<XElement> targetNodes = from target in rootNode.Descendants("User")
 8                                                         where target.Element("Name").Value=="Mary"
 9                                                         select target;
10                     //遍历所获得的目标节点(集合)
11                     foreach (XElement node in targetNodes)
12                     {
13                         //将用户名为Mary的User节点修改为Emma
14                         node.Element("Name").SetValue("Emma");
15                         node.Element("Description").SetValue("I am Emma");
16                     }
17                     //保存对xml的更改操作
18                     rootNode.Save(xmlPath);
19                 }
20                 catch (Exception ex)
21                 {
22                     Console.WriteLine(ex.ToString());
23                 }
24             }
View Code

修改后的xml文件如下所示:

四、添加新节点

 1      public static void AddXmlNodeInformation(string xmlPath)
 2             {
 3                 try
 4                 {
 5                     //定义并从xml文件中加载节点(根节点)
 6                     XElement rootNode = XElement.Load(xmlPath);
 7                     //定义一个新节点
 8                     XElement newNode = new XElement("User", new XAttribute("Id", "4"),
 9                                                                 new XElement("Name", "Rose"),
10                                                                 new XElement("Password", "333333"),
11                                                                 new XElement("Description", "I am Rose"));
12                     //将此新节点添加到根节点下
13                     rootNode.Add(newNode);
14                     //保存对xml的更改操作
15                     rootNode.Save(xmlPath);
16                 }
17                 catch (Exception ex)
18                 {
19                     Console.WriteLine(ex.ToString());
20                 }
21             }
View Code

结果如下:

五、删除节点

 1   public static void DeleteXmlNodeInformation(string xmlPath)
 2             {
 3                 try
 4                 {
 5                     //定义并从xml文件中加载节点(根节点)
 6                     XElement rootNode = XElement.Load(xmlPath);
 7                     //查询语句: 获取ID属性值等于"999999"的所有User节点
 8                     IEnumerable<XElement> targetNodes = from target in rootNode.Descendants("User")
 9                                                         let id= Convert.ToInt32(target.Attribute("Id").Value)
10                                                         where id >=3
11                                                         select target;
12 
13                     targetNodes.Remove();
14                     //保存对xml的更改操作
15                     rootNode.Save(xmlPath);
16                     
17                 }
18                 catch (Exception ex)
19                 {
20                     Console.WriteLine(ex.ToString());
21                 }
22             }
View Code

运行结果如下:

 六、实际应用---判断桌面上是否存在指定文件以及具体路径

 1    private static string FileQuery(string targetFileName)
 2         {
 3             string myDeskTopDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
 4             string []fileNames = Directory.GetFiles(myDeskTopDir, "*.*", SearchOption.AllDirectories);
 5             List<FileInfo> files = new List<FileInfo>();
 6             foreach(var fileName in fileNames)
 7             {
 8                 files.Add(new FileInfo(fileName));
 9             }
10             var results = from file in files
11                           where file.Name == targetFileName
12                           select file;
13             StringBuilder queryResult = new StringBuilder();
14             foreach(var result in results)
15             {
16                 queryResult.AppendLine("Query Result:" + result.FullName);
17             }
18             return queryResult.ToString();
19         }
View Code

 

posted on 2018-09-18 16:27  缘惜  阅读(510)  评论(0编辑  收藏  举报