C#-使用Linq从XML文件加载哈希集字典



我有一个包含标识符的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<string, HashSet<string>>()中,其中键是每个类别,哈希集包含每个容器值。

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

谢谢!

使用此设置代码:

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)));

最新更新