码迷,mamicode.com
首页 > Windows程序 > 详细

C# 解析XML

时间:2016-03-18 15:54:01      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

解析文件内容:

 

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 
 3 <users>
 4   <user id="1001">
 5     <name>张三</name>
 6     <email>123456789@136.com</email>
 7     <phone>13400000000</phone>
 8   </user>
 9   <user id="1002">
10     <name>李四</name>
11     <email>123456789@126.com</email>
12     <phone>15800000000</phone>
13   </user>
14 </users>

 

解析代码:

 1 static void ReadParseXml()
 2 {
 3     XmlDocument xmlDoc = new XmlDocument();
 4     xmlDoc.Load("E:/Data/VisualStudio/C#/app001/ConsoleApp/App01/userlist.xml");
 5     //查找<users>
 6     XmlNode root = xmlDoc.SelectSingleNode("users");
 7     //获取到所有<users>的子节点
 8     XmlNodeList nodeList =root.ChildNodes;
 9     //遍历所有子节点
10     foreach (XmlNode xn in nodeList)
11     {
12         XmlElement xe = (XmlElement)xn;
13         XmlNodeList subList = xe.ChildNodes;
14         foreach (XmlNode xmlNode in subList)
15         {
16             if ("name".Equals(xmlNode.Name))
17             {
18                 Console.WriteLine("姓名:" + xmlNode.InnerText);
19             }
20             else if ("email".Equals(xmlNode.Name))
21             {
22                 Console.WriteLine("邮箱:" + xmlNode.InnerText);
23             }                  
24         }            
25     }
26 }
27 
28 
29 
30 
31 static void ReadParseXml2()
32 {
33     XmlDocument xmlDoc = new XmlDocument();
34     xmlDoc.Load("E:/Data/VisualStudio/C#/app001/ConsoleApp/App01/userlist.xml");
35     //查找<users>
36     XmlNode root = xmlDoc.SelectSingleNode("users");
37     //获取到所有<users>的子节点
38     XmlNodeList nodeList = xmlDoc.SelectSingleNode("users").ChildNodes;
39     //遍历所有子节点
40     foreach (XmlNode xn in nodeList)
41     {
42         XmlElement xe = (XmlElement)xn;
43         Console.WriteLine("节点的ID为: " + xe.GetAttribute("id"));
44         XmlNodeList subList = xe.ChildNodes;
45         foreach (XmlNode xmlNode in subList)
46         {
47             Console.WriteLine(xmlNode.InnerText);
48         }
49     }
50 }

 

C# 解析XML

标签:

原文地址:http://www.cnblogs.com/BookCode/p/5292249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!