C# 解析XML
解析文件内容:
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 }
一叶乘风自飘流,飘零四海散忧愁!