2015-04-06 59 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