开发者

How to compare dictonary key with xml attribute value in xml using LINQ in c #?

开发者 https://www.devze.com 2022-12-31 17:58 出处:网络
i\'ve a dictonary \" dictSample \" which contains 1 data1 2 data2 3 data3 4 data4 and an xml file\"sample.xml\" in the form of:

i've a dictonary " dictSample " which contains

1 data1
2 data2
3 data3
4 data4

and an xml file"sample.xml" in the form of:

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

i need to match the dictonary keys with the xml attribute id and to insert the matching id and 开发者_如何学Pythonthe value of attribute"value" into another dictonary

now i'm using like:

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());
            }
        }

please help me to do this in a simple way using LINQ


You probably want this:

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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号