<?xml version="1.0" encoding="utf-8"?>
<Groups>
  <Group ID="1">公司</Group>
  <Group ID="4">个人</Group>
  <Group ID="5">亲人</Group>
  <Group ID="7">朋友</Group>
</Groups>怎么把这个XML里面的ID 与后面的名字做为键值存入Dictionary<string,string>里啊?比如("1","公司")这样的格式

解决方案 »

  1.   

    可以用dom读取方式。xmldocument,获取到groups结点下的所有子节点,nodelist.然后遍历nodelist就可以。
      

  2.   

    ID可以用Element.GetAttribute()方法获取。'公司'可以用Element.Value获取。
      

  3.   


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;namespace XmlDoc
    {
        class Program
        {
            static void Main(string[] args)
            {
                string xmlFileName = @"D:\Fillex\VS2008Projects\CSDNAnswer\XmlDoc\XmlDoc\data.xml";
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlFileName);            Dictionary<string, string> dict = new Dictionary<string, string>();
                foreach (XmlNode node in xmlDoc.SelectNodes("//Group"))
                {
                    dict.Add(node.Attributes["ID"].Value, node.InnerText);
                }            foreach (var keyvalue in dict)
                    Console.WriteLine("{0}:{1}", keyvalue.Key, keyvalue.Value);            Console.ReadLine();
            }
        }
    }
      

  4.   

                string xml = @"<Groups>
      <Group ID=""1"">公司</Group>
      <Group ID=""4"">个人</Group>
      <Group ID=""5"">亲人</Group>
      <Group ID=""7"">朋友</Group>
    </Groups>";            System.Collections.Generic.Dictionary<string, string> _list = new Dictionary<string, string>();
                foreach (var v in XDocument.Parse(xml).Descendants("Group"))
                {
                    _list.Add(v.Attribute("ID").Value,v.Value);
                }
      

  5.   


    XElement xe = XElement.Load("../../XMLFile1.xml");
    Dictionary<int, string> dic = xe.Descendants("Group").ToDictionary(s => int.Parse(s.Attribute("ID").Value), v => v.Value);