如何在c#中使用LINQ将字典键与xml中的xml属性值进行比较?

时间:2010-05-25 04:21:13

标签: c# xml linq

我有一个包含

的dictonary“dictSample”
1 data1
2 data2
3 data3
4 data4

和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>

我需要将dictonary键与xml属性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

以简单的方式帮助我这样做

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);