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