XDocument to Dictionary
本文关键字:Dictionary to XDocument | 更新日期: 2023-09-27 18:04:33
这是我的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;
var doc = XDocument.Load(filePath);
var dict = doc.Root.Elements("city")
.ToDictionary(c => (string)c.Element("CityName"),
c => (string)c.Element("CityId"));
棘手的问题-为什么您希望CityId
作为字符串,而不是int
?
另一种方式
Dictionary<string, string> dictionary = new Dictionary<string,string>();
foreach (XmlNode node in nodeList)
{
dictionary.Add(node.ChildNodes[0].InnerText, node.ChildNodes[1].InnerText);
}