0

这是我的 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;
4

2 回答 2

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?

于 2013-03-19T07:54:04.293 回答
1

另一种方式

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

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

    }
于 2013-03-19T08:13:31.177 回答