2015-04-06 60 views
1

我有一个XML文件,其中包含我想要添加到哈希集字典以供稍后分析的标识符。C# - 使用Linq从XML文件加载哈希集字典

我很困惑如何使用linq从XML文件填充这个Hashsets字典。我曾尝试在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>>()其中关键是每个类别和HashSet中包含每个集装箱价值。

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

谢谢!

回答

2

有了这个设置代码:

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

这工作得很好!非常感谢。我创建XML文档的方式很好吗?我注意到它与我在其他人看到的有所不同,它们在我看到的stackoverflow – user3369494

+1

@ user3369494:如果你不知道更多关于你正在处理的数据的类型,很难说什么是“好”。它看起来足够有效。 – StriplingWarrior