使用linq从xml获取键值对

时间:2009-11-11 15:38:02

标签: c# linq

如何使用linq:

从此xml示例中提取键值对
<foo>
<add key="key1" Value="val1"/>
<add key="key2" Value="val2"/>
<add key="key3" Value="val3"/>
<foo/>

2 个答案:

答案 0 :(得分:7)

试试这个:

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

答案 1 :(得分:2)

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