您的位置:首页 > 编程语言 > C#

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

2016-10-17 08:35 375 查看
镇场诗:
    清心感悟智慧语,不着世间名与利。学水处下纳百川,舍尽贡高我慢意。
    学有小成返哺根,愿铸一良心博客。诚心于此写经验,愿见文者得启发。
——————————————————————————————————————————

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 效果



注:舍名利 喜欢看儒释道的书籍,所以举的不是普通例子,但效果都是一样的,还望能看得过去。

——————————————————————————————————————————
博文的精髓,在技术部分,更在镇场一诗。版本:VS2015 系统:Windows 7
C#是优秀的语言,值得努力学习。我是跟随 传智播客\黑马 .Net视频教程学习的。
如果博文的内容有可以改进的地方,甚至有错误的地方,请留下评论,我一定努力改正,争取铸成一个良心博客。
注:此文仅作为科研学习,如果我无意中侵犯了您的权益,请务必及时告知,我会做出改正。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: