6

我有一个如下所示的 XML 文件:

<Cities>
    <Name>Seattle</Name>
    <State>WA</State>
    <Population>552105</Population>
</Cities>

我想将城市信息加载到字典中,以便我的字典看起来像:

cityDictionary("Name") = "Seattle"
cityDictionary("State") = "WA"
cityDictionary("Population") = "552105"

以下代码确实有效:

var doc = XDocument.Load(@"..\..\Cities.xml");
var rootNodes = doc.Root.DescendantNodes().OfType<XElement>();
var keyValuePairs = from n in rootNodes
                    select new
                    {
                        TagName = n.Name,
                        TagValue = n.Value
                    };

Dicitionary<string, string> allItems = new Dictionary<string, string>();
foreach (var token in keyValuePairs) {
    allItems.Add(token.TagName.ToString(), token.TagValue.ToString());
}

但我想做这一步。

有什么建议么?

4

4 回答 4

12

为什么这么复杂?以下是您可以在方法链语法中执行此操作的方法:

var allItems = rootNodes.ToDictionary(n => n.Name.ToString(), n => n.Value);

或者只是作为一个普通的旧循环,如果您需要使用旧版本的 C# 或者想要保持老式的东西:

var allItems = new Dictionary<string, string>();
foreach (var node in rootNodes)
{
    allItems.Add(node.Name.ToString(), node.Value);
}
于 2012-08-14T15:36:20.133 回答
5

试试这个ToDictionary.

    Dictionary<string, string> allItems = rootNodes.ToDictionary(v => v.Name, v => v.Value);
于 2012-08-14T15:31:56.763 回答
0

在此示例中,您必须确保将 TagName 转换为字符串

Dictionary<string, string> allItems = (from n in rootNodes
select new
            {
                TagName = n.Name,
                TagValue = n.Value
            }).ToDictionary(v => v.TagName.ToString(), v => v.TagValue);

或将 XName 存储为密钥

Dictionary<XName, string> allItems = (from n in rootNodes
select new
            {
                TagName = n.Name,
                TagValue = n.Value
            }).ToDictionary(v => v.TagName, v => v.TagValue);
于 2012-08-14T15:38:58.463 回答
0
var element = xmlDoc.Root.Element("Cities");
            if (element != null)
            {
                var idList = element.Descendants().Where(p_ => p_.Name == "Name").Select(v_ => v_.Value).ToArray();
                var valList = element.Descendants().Where(p_ => p_.Name == "Population").Select(v_ => v_.Value).ToArray();

                var citiesDictionary = idList.Zip(valList, (key_, value_) => new { k = key_, v = value_ }).ToDictionary(x_ => x_.k, x_ => x_.v);
于 2015-06-08T05:43:12.440 回答