2010-05-25 62 views
1

我已經包含如何在xml中使用LINQ在c#中將dictonary關鍵字與xml屬性值進行比較?

1 data1 
2 data2 
3 data3 
4 data4 

一個dictonary 「dictSample」,並在形式的XML文件 「sample.xml中」:

<node> 
<element id="1" value="val1"/> 
<element id="2" value="val2"/> 
<element id="3" value="val3"/> 
<element id="4" value="val4"/> 
<element id="5" value="val5"/> 
<element id="6" value="val6"/> 
<element id="7" value="val7"/> 
</node> 

我需要以匹配XML的dictonary鍵屬性ID和插入匹配ID和 屬性「值」的值插入到另一dictonary

現在,我使用這樣的:

XmlDocument XDOC = new XmlDocument(); 
XDOC.Load("Sample.xml"); 
XmlNodeList NodeList = XDOC.SelectNodes("//element"); 
Dictionary<string, string> dictTwo = new Dictionary<string, string>(); 
foreach (string l_strIndex in dictSample .Keys) 
     { 
      foreach (XmlNode XNode in NodeList) 
      { 
       XmlElement XEle = (XmlElement)XNode; 
       if (dictSample[l_strIndex] == XEle.GetAttribute("id")) 
        dictTwo.Add(dictSample[l_strIndex], XEle.GetAttribute("value").ToString()); 
      } 
     } 

請幫我使用LINQ

回答

0
Dictonary<string,string> dict2=new Dictonary<string,string>() 
    XDocument XDOC=XDocument.Load("sample.xml"); 
    dict2=(from key in dictSample from element in XDOC.Descendants("element") where 
      key.Value == element.Attribute("id").Value select new { ID = 
      element.Attribute("id").Value,Val = element.Attribute 
      ("value").Value}).ToDictionary(X => X.ID, X => X.Val); 
1

這樣做以簡單的方式你可能想這樣的:

var q = from x in NodeList.Cast<XmlElement>() 
    join k in dictSample on x.GetAttribute("id") equals k.Value 
    select new { Key = k.Value, Value = x.GetAttribute("value").ToString() }; 

dictTwo = q.ToDictionary(x => x.Key); 
相關問題