XDocument to Dictionary

时间:2013-03-19 07:50:28

标签: c# linq linq-to-xml

这是我的Xdocument:

<Response>
    <city>
        <CityName>xxx</CityName>
        <CityId>1</CityId>
    </city>
    <city>
        <CityName>yyy</CityName>
        <CityId>2</CityId>
    </city>   
</Response>

如何将其存储在Dictionary(cityname,cityid)

Dictionary<string, string > dictionary;

2 个答案:

答案 0 :(得分:5)

var doc = XDocument.Load(filePath);
var dict = doc.Root.Elements("city")
                   .ToDictionary(c => (string)c.Element("CityName"),
                                 c => (string)c.Element("CityId"));

棘手的问题 - 为什么您希望CityId为字符串,而不是int

答案 1 :(得分:1)

另一种方式

    Dictionary<string, string> dictionary = new Dictionary<string,string>();

    foreach (XmlNode node in nodeList)
    {
        dictionary.Add(node.ChildNodes[0].InnerText, node.ChildNodes[1].InnerText);

    }