tags:

views:

83

answers:

2

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/>
+2  A: 

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();
Jon Skeet
hi, this won't compile. I'm getting: 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type
raklos
grr...nevermind! using System.Linq; needed do'h
raklos
In place of the ToList(); I would be tempted to use a: .ToDictionary(item => item.Key, item => item.Value); Just as seems more obvious to me for OP's problem.
Mike
+1  A: 
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...
Murph
I think you mean Attribute rather than Attributes, and Elements only takes a single element name, not a path (AFAIK, anyway).
Jon Skeet