【问题标题】:C# - Load dictionary of Hashsets from an XML file using LinqC# - 使用 Linq 从 XML 文件加载哈希集字典
【发布时间】:2015-04-06 18:48:19
【问题描述】:

我有一个包含标识符的 XML 文件,我想将其添加到哈希集字典中以供以后解析。

我对如何使用 linq 从 XML 文件填充此哈希集字典感到困惑。我曾尝试在 stackoverflow 上使用其他帖子,但我的 XML 文件的填充方式与我见过的其他帖子不同。

目前我的 XML 文件如下所示:

    <Release_Note_Identifiers>
      <Identifier container ="Category1">
        <Container_Value>Old</Container_Value>
        <Container_Value>New</Container_Value>
      </Identifier>
      <Identifier container ="Category2">
        <Container_Value>General</Container_Value>
        <Container_Value>Liquid</Container_Value>
      </Identifier>
      <Identifier container ="Category3">
        <Container_Value>Flow Data</Container_Value>
        <Container_Value>Batch Data</Container_Value>
      </Identifier>
      <Identifier container ="Category4">
        <Container_Value>New Feature</Container_Value>
        <Container_Value>Enhancement</Container_Value>
      </Identifier>
    </Release_Note_Identifiers>

我想将所有这些添加到Dictionary&lt;string, HashSet&lt;string&gt;&gt;(),其中键是每个类别,哈希集包含每个容器值。

我想让它尽可能抽象,因为我想最终添加更多类别并为每个类别添加更多容器值。

谢谢!

【问题讨论】:

    标签: c# xml linq dictionary linq-to-xml


    【解决方案1】:

    使用此设置代码:

    var contents = @"    <Release_Note_Identifiers>
        <Identifier container =""Category1"">
            <Container_Value>Old</Container_Value>
            <Container_Value>New</Container_Value>
        </Identifier>
        <Identifier container =""Category2"">
            <Container_Value>General</Container_Value>
            <Container_Value>Liquid</Container_Value>
        </Identifier>
        <Identifier container =""Category3"">
            <Container_Value>Flow Data</Container_Value>
            <Container_Value>Batch Data</Container_Value>
        </Identifier>
        <Identifier container =""Category4"">
            <Container_Value>New Feature</Container_Value>
            <Container_Value>Enhancement</Container_Value>
        </Identifier>
        </Release_Note_Identifiers>";
    var xml = XElement.Parse(contents);
    

    ...以下将为您提供您想要的。

    var dict = xml.Elements("Identifier")
        .ToDictionary(
            e => e.Attribute("container").Value,
            e => new HashSet<string>(
                e.Elements("Container_Value").Select(v=> v.Value)));
    

    【讨论】:

    • 这很好用!太感谢了。我创建 XML 文档的方式好吗?我注意到它与我在 stackoverflow 上看到的其他不同
    • @user3369494:如果不了解您正在处理的数据类型,很难说什么是“好”。它看起来足够有效。
    猜你喜欢
    • 2016-08-12
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多