首页 > 代码库 > C# XML 输出xml根节点下的直接(第一级)子节点所有的属性的名字和值

C# XML 输出xml根节点下的直接(第一级)子节点所有的属性的名字和值

1 xml文件内容

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <cultures>
 3 
 4     <daojia count="100" comment="good">
 5         <book> 
 6             <name> 道德经</name>
 7             <author>老子</author>
 8         </book>
 9         <book > 
10             <name> 文始真经</name>
11             <author>关尹子</author>
12         </book>
13     </daojia>
14 
15     <fojia count="321" comment="good">
16         <book >
17             <name>金刚经</name>
18             <author>释迦牟尼佛</author>
19         </book>
20         <book>
21             <name>地藏菩萨本愿经</name>
22             <author>地藏王菩萨</author>            
23         </book>
24     </fojia> 
25           
26 </cultures>

 

 

2 代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Xml.Linq;
 7 
 8 namespace ConsoleApplication8
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             //1.xml文件的格式必须是正确的
15             XDocument file = XDocument.Load("1.xml");
16             
17             //获取xml文件的根节点
18             XElement xmlRoot = file.Root;
19 
20             //获取根节点下的第一级子节点
21             IEnumerable<XElement> nodeFirst=xmlRoot.Elements();
22 
23             foreach (var item in nodeFirst)
24             {
25 
26                 var iAttres= item.Attributes();
27                 foreach (var i in iAttres)
28                 {
29                     Console.WriteLine(i.Name+" "+i.Value);
30                 }
31             }
32 
33             Console.ReadKey();
34         }
35     }
36 }

 

 

3 效果

技术分享

C# XML 输出xml根节点下的直接(第一级)子节点所有的属性的名字和值