2013-05-03 77 views
0

我有以下格式一些XML:有查了字典包含的XElement屬性值

<select> 
    <option value="2" ID="451">Some other text</option> 
    <option value="5" ID="005">Some other text</option> 
    <option value="6" ID="454">Some other text</option> 
    <option value="15" ID="015">Some other text</option> 
    <option value="17" ID="47">Some other text</option> 
</select> 

我也有,我想匹配的相關選項中的ID的鍵值的字典上面的xml並返回字典值。我不確定如何實現這一點。

我想循環輪字典,像這樣的:

 foreach (KeyValuePair<string, string> dictionaryEntry in dictionary) 
     { 
      if (dictionaryEntry.Key == "AttributeValue") 
      { 
       //do stuff here 

      } 
     } 

但我不確定如何比較? 感謝

+2

因爲你沒有代碼,我不會提供一個答案,而只是一般的指導。使用xml解析器解析出您用作字典關鍵字的值。通過執行'Dictionary [parsedOutOfXml]'獲取字典值。有很多在c#中解析xml的例子。 – evanmcdonnal 2013-05-03 15:53:58

+0

創建詞典的代碼在哪裏?一本字典是什麼?選項ID,值(即ID是鍵和值是值?) – Neolisk 2013-05-03 16:10:41

+0

我已經有一個填充字典。其中一個條目的關鍵值應該與以上選項節點的ID屬性值之一匹配。如果它確實想要返回字典的值,如果不是什麼都不做。 – PorkyGimp 2013-05-03 16:17:36

回答

0

像這樣的東西應該工作:

class Program 
{ 
    static void Main(string[] args) 
    { 

     String xmlString = @"<select> 
     <option value=""2"" ID=""451"">Some other text</option> 
     <option value=""5"" ID=""005"">Some other text</option> 
     <option value=""6"" ID=""454"">Some other text</option> 
     <option value=""15"" ID=""015"">Some other text</option> 
     <option value=""17"" ID=""47"">Some other text</option> 
     </select>"; 

     Dictionary<string, string> theDict = new Dictionary<string, string>(); 
     theDict.Add("451", "Dict Val 1"); 
     theDict.Add("005", "Dict Val 2"); 
     theDict.Add("454", "Dict Val 3"); 
     theDict.Add("015", "Dict Val 4"); 
     theDict.Add("47", "Dict Val 5"); 

     using (XmlReader reader = XmlReader.Create(new StringReader(xmlString))) 
     { 
      XmlWriterSettings ws = new XmlWriterSettings(); 
      ws.Indent = true; 
      while (reader.Read()) 
      { 
       switch (reader.NodeType) 
       { 
        case XmlNodeType.Element: 
         if (reader.Name == "option") 
         { 
          System.Diagnostics.Debug.WriteLine(String.Format("ID: {0} \nValue: {1} \nDictValue: {2}", reader.GetAttribute("ID"), reader.GetAttribute("value"), theDict[reader.GetAttribute("ID")])); 
         } 
         break; 
       } 

      } 
     } 
    } 
} 

我真的不知道什麼是你提到的,但我的猜測是你3個不同的值總體而言,「價值」,在XML字典,xml中的ID以及字典中的另一個值和字典中的鍵是xml中的ID。假設所有這些都是正確的,那麼這將從你的xml中獲得你所需要的。

0

您可以從您的xml &創建一個字典,然後獲取基於密鑰的值。

例如,

XDocument doc1 = XDocument.Load(XmlFileName); 
var elements1 = (from items in doc1.Elements("select").Elements("option") 
          select items).ToDictionary(x => x.Attribute("ID").Value, x => x.Attribute("value").Value);