解析文件內容: 解析代碼:
解析文件內容:
1 <?xml version="1.0" encoding="utf-8" ?> 2 3 <users> 4 <user id="1001"> 5 <name>張三</name> 6 <email>[email protected]</email> 7 <phone>13400000000</phone> 8 </user> 9 <user id="1002"> 10 <name>李四</name> 11 <email>[email protected]</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 }