首页 > 代码库 > C# XML 输出xml根节点下的直接(第一级)子节点的内容

C# XML 输出xml根节点下的直接(第一级)子节点的内容

1 xml文件内容

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <cultures>
 3 
 4     <daojia>
 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>
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             //获取xml文件的根节点
17             XElement xle = file.Root;
18 
19 
20             IEnumerable<XElement> ixt=xle.Elements();
21 
22             foreach (var item in ixt)
23             {
24                 Console.WriteLine(item);
25             }
26 
27             Console.ReadKey();
28         }
29     }
30 }

 

 

 

3 效果

技术分享

C# XML 输出xml根节点下的直接(第一级)子节点的内容