C # Parse XML,
Parse file content:
1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 3 <users> 4 <user id = "1001"> 5 <name> Zhang San </name> 6 <email> 123456789@136.com </email> 7 <phone> 13400000000 </phone> 8 </user> 9 <user id = "1002"> 10 <name> Li Si </name> 11 <email> 123456789@126.com </email> 12 <phone> 15800000000 </ phone> 13 </user> 14 </users>
Parsing Code:
1 static void ReadParseXml () 2 {3 XmlDocument xmlDoc = new XmlDocument (); 4 xmlDoc. load ("E:/Data/VisualStudio/C #/app001/ConsoleApp/App01/userlist. xml "); 5 // search for <users> 6 XmlNode root = xmlDoc. selectSingleNode ("users"); 7 // obtain all <users> subnodes 8 XmlNodeList nodeList = root. childNodes; 9 // traverse all sub-nodes 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 ("name:" + xmlNode. innerText); 19} 20 else if ("email ". equals (xmlNode. name) 21 {22 Console. writeLine ("Email:" + 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 // search for <users> 36 XmlNode root = xmlDoc. selectSingleNode ("users"); 37 // obtain all <users> subnodes 38 XmlNodeList nodeList = xmlDoc. selectSingleNode ("users "). childNodes; 39 // traverse all subnodes 40 foreach (XmlNode xn in nodeList) 41 {42 XmlElement xe = (XmlElement) xn; 43 Console. writeLine ("Node ID:" + xe. getAttribute ("id"); 44 XmlNodeList subList = xe. childNodes; 45 foreach (XmlNode xmlNode in subList) 46 {47 Console. writeLine (xmlNode. innerText); 48} 49} 50}