这是我的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;
答案 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);
}