【问题标题】:Insert a XML in a Dictionary using LINQ in C#在 C# 中使用 LINQ 在字典中插入 XML
【发布时间】:2014-05-30 07:59:08
【问题描述】:

我有这个 XML 文件:

<RootNode>
    <Node1>Value1</Node1>
    <Node2>Value2</Node2>
    <Node3>Value3</Node3>
    <Node4>
        <SubNode1>SubValue1</SubNode1>
        <SubNode2>SubValue2</SubNode2>
        <SubNode3>SubValue3</SubNode3>
        <SubNode4>SubValue4</SubNode4>
    </Node4>
    <Node4>
        <SubNode1>SubValue1</SubNode1>
        <SubNode2>SubValue2</SubNode2>
        <SubNode3>SubValue3</SubNode3>
        <SubNode4>SubValue4</SubNode4>
    </Node4>
</RootNode>

我有更多像“Node4”这样的节点。我想用 LINQ 将这些项目保存在字典中,但我做不到。

谢谢!

编辑:

我只尝试这个(对不起代码,但我是 LINQ 的新手,这个代码只尝试插入节点 4 及其子节点):

XDocument xDocument = XDocument.Load(streamReader);
Dictionary<string, List<string>> datas = new Dictionary<string, List<string>>();

foreach (XElement item in xDocument.Root.Elements().Where(x => x.Elements().Count() > 0))
{
    datas.Add(item.Name.LocalName, item.Elements("SubNode1").Select(x => x.Value).ToList());
}

但这会在第二次迭代时返回重复键的错误。这很正常,因为其他的Node4也叫Node4。

【问题讨论】:

  • 如果 subnote1 是值,你的字典键是什么?我会更多地看到一个列表而不是字典
  • 您到底想在字典中存储什么?
  • 我想插入所有节点及其值,对于节点 4,我想在同一个字典中插入作为键 SubNode1 值和作为值的其余部分的 List值。

标签: c# xml linq dictionary


【解决方案1】:

你可以这样做:

var datas = xDocument.Root.Elements()
                .Select(
                    e => e.Descendants().Count() > 0?
                    new { 
                        key = e.Descendants().Single(x => x.Name.LocalName == "SubNode1").Value,
                        value =  e.Descendants().Select(x => x.Value).ToList()
                        }:
                    new { 
                        key = e.Name.LocalName, 
                        value = new List<string>(){ e.Value } 
                        }
                ).ToDictionary( k => k.key, v => v.value );

【讨论】:

  • 为什么?没有解释的代码不是很有帮助。在这种情况下,它可能对 OP 有所帮助,但对路过的 Google 员工没有帮助。
  • @Patrick Hofman:解释:过滤->选择->投影->转换
  • 嗨!,使用此代码,我遇到了密钥重复的问题,因为 Node4 在所有重复项中都称为“Node4”。我将编辑主要消息,以便为您提供更好的信息。
  • @user3535054:您不能在字典中的同一个键下有两个项目。密钥必须是唯一的。是否可以接受另一种用于存储结果的集合类型?
  • Nodes4 的键必须是每个“Node4”的“SubValue1”。我编辑了第一条消息,因为我的值有误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多