C# 入门操作XML文件实例
首先看下XML文件的结构:
1 <?xml version="1.0" encoding="utf-8" ?> 2 <List> 3 4 <Item id="81" country="Japan"></Item> 5 <Item id="852" country="香港特别行政区"></Item> 6 <Item id="886" country="台灣"></Item> 7 <Item id="86" country="中国"></Item> 8 <Item id="213" country="Algeria"></Item> 9 <Item id="54" country="Argentina"></Item> 10 <Item id="61" country="Australia"></Item> 11 <Item id="880" country="Bangladesh"></Item> 12 <Item id="591" country="Bolivia"></Item> 13 <Item id="673" country="Brunei"></Item> 14 <Item id="1" country="USA"></Item> 15 <Item id="56" country="Chile"></Item> 16 <Item id="57" country="Colombia"></Item> 17 <Item id="506" country="Costa Rica"></Item> 18 <Item id="357" country="Cyprus"></Item> 19 <Item id="593" country="Ecuador"></Item> 20 <Item id="20" country="Egypt"></Item> 21 <Item id="33" country="France"></Item> 22 <Item id="502" country="Guatemala"></Item> 23 <Item id="504" country="Honduras"></Item> 24 <Item id="91" country="India"></Item> 25 <Item id="62" country="Indonesia"></Item> 26 <Item id="353" country="Ireland"></Item> 27 <Item id="962" country="Jordan"></Item> 28 </List>
一个简单的国家(地区)电话编号对应的国家(地区)
需求如下:根据代号查找国家
1 /// <summary> 2 /// 根据国家电话代号查找国家 3 /// </summary> 4 /// <param name="code">国家电话代号</param> 5 /// <returns>国家名称</returns> 6 public string GetCountryByCode(string code) 7 { 8 string count = ""; 9 10 string xmlfile = HttpContext.Current.Server.MapPath("~/XML/CodeToCountry/country.xml"); 11 12 System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); 13 doc.Load(xmlfile); 14 System.Xml.XmlNodeList nodes = doc.SelectNodes("List/Item"); 15 foreach (System.Xml.XmlNode item in nodes) 16 { 17 if (code == item.Attributes["id"].Value) 18 { 19 count = item.Attributes["country"].Value; 20 } 21 } 22 return count; 23 }

浙公网安备 33010602011771号