在C#中 遍历XML文件的所有节点

本文纪录的内容为:循环遍历XML文件的所有节点的方法,思路就是当遇到某一个节点包含子节点时,继续循环遍历。如果对循环子节点的位置有特殊的需求,适当做出修改即可。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Xml.Linq;
 5 
 6 namespace Tool
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12 
13             XDocument xmlDocument = XDocument.Load(@"C:\Users\TestFile.xml");
14             Dictionary<string, string> elementDic = new Dictionary<string, string>();
15             GetElements(xmlDocument.Root.Elements(), "Objects", elementDic, "Left");
16             foreach (var item in elementDic)
17             {
18                 Console.WriteLine("properites names:{0} properites values:{1}", item.Key, item.Value);
19             }
20             Console.ReadLine();
21         }
22 
23         /// <summary>
24         /// 将XML中的内容全部读取出来
25         /// </summary>
26         /// <param name="xElements"></param>
27         /// <param name="parentNodeName"></param>
28         /// <param name="elementDic"></param>
29         /// <param name="dictionaryValue"></param>
30         public static void GetElements(IEnumerable<XElement> xElements,string parentNodeName, Dictionary<string, string> elementDic,string dictionaryValue)
31         {
32             
33             foreach (XElement item in xElements)
34             {
35                 if (item.HasElements)
36                 {
37                     GetElements(item.Elements(), parentNodeName+item.Name.ToString(), elementDic, dictionaryValue);
38                 }
39                 else
40                 {
41                     elementDic.Add(parentNodeName + item.Name + item.Value, dictionaryValue);
42                 }
43             }
44         }
45     }
46 }

 

在C#中 遍历XML文件的所有节点

上一篇:C# List 行转列


下一篇:win10家庭版VMware,禁用Device/Credential Guard不兼容问题