Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get key value pairs from xml using linq

Tags:

c#

linq

How can i extract key value pairs from this xml example using linq:

<foo>
<add key="key1" Value="val1"/>
<add key="key2" Value="val2"/>
<add key="key3" Value="val3"/>
<foo/>
like image 596
raklos Avatar asked Dec 30 '22 11:12

raklos


2 Answers

Try this:

string text = "<foo>...</foo>";
var pairs = XDocument.Parse(text)
                     .Descendants("add")
                     .Select(x => new { Key = x.Attribute("key").Value,
                                        Value = x.Attribute("Value").Value })
                     .ToList();
like image 187
Jon Skeet Avatar answered Jan 01 '23 16:01

Jon Skeet


XDocument fooXML = new XDocument.Load("foo.xml")
var query = from a in fooXML.Element("foo").Elements("add")
            select new
            {
                key = a.Attribute("key").Value,
                val = a.Attribute("Value").Value
            };
// Then do what you want with the query...
like image 43
Murph Avatar answered Jan 01 '23 17:01

Murph