<?xml version="1.0" encoding="utf-8" ?> 
<root> 
  <city name="沈阳" number="024"/> 
  <city name="大连" number="0411"/> 
  <city name="长春" number="0431"/> 
  <city name="北京" number="010"/> 
  <city name="天津" number="022"/> 
  <city name="鞍山" number="0412"/> 
</root> 将该文件保存为“XMLFile.xml” 
再用以下类读取 
C# codepublicclass XmlInfo 
        {private XmlDocument _xmldoc=new XmlDocument();public XmlInfo() 
            { 
                _xmldoc.Load("XMLFile.xml"); 
            }publicstring GetPlacename(string number) 
            { 
                XmlNode root= _xmldoc.DocumentElement; 
                XmlElement elem= (XmlElement)root.SelectSingleNode("//*[@number='"+number+"']");return elem.Attributes["name"].Value; 
            } 
        } 调用方法:  
C# code 
XmlInfo info = new XmlInfo();
            textBox2.Text = info.GetPlacename(textBox1.Text);就是假设WINFORM里有一按扭button1,两文本框textbox1,textbox2,我想让他实现的是在textbox1里输入一个区号,然后点击按扭,就可以在textbox2里显示出所在位置
现在问题基本上解决,但我忽略一个问题,那就是如果用户在textbox1里输入的区号是在xml里没定义的区号,那就会发生异常,所以想请高手帮加一个如果输入xml里没有的区号时会弹出一个messagebox的代码,谢谢了..

解决方案 »

  1.   

    static void Main(string[] args)
            {
                string name = GetPlacename("024",args[0]);
                Console.WriteLine(name);
            }        public static string GetPlacename(string number,string fileName)
            {
                try
                {
                    Dictionary<string, string> myDictionary = new Dictionary<string, string>();
                    XmlDocument xdoc = new XmlDocument();
                    xdoc.Load(fileName);                XmlNodeList nodes = xdoc.SelectSingleNode("root").ChildNodes;                foreach (XmlNode node in nodes)
                    {
                        myDictionary.Add(node.Attributes["number"].Value, node.Attributes["name"].Value);
                    }                if (!string.IsNullOrEmpty(myDictionary[number]))
                    {
                        return myDictionary[number];
                    }
                    else
                    {
                        return null;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return null;
                }
            }
      

  2.   

    忘记说明了. args[0]是我本地的xml文件路径,你看着换为你的文件路径,
    我的做法是先把所有的都取出来放在一个Dictionary里面,然后好判断,是否存在.
      

  3.   

    当然你也可以在你的form里面改一下,MessageBox.Show().....