简体   繁体   中英

get key value pairs from xml using 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/>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM