从XML键值对如何使用LINQ我提取此XML例如键值对:获得使用LINQ
<foo>
<add key="key1" Value="val1"/>
<add key="key2" Value="val2"/>
<add key="key3" Value="val3"/>
<foo/>
从XML键值对如何使用LINQ我提取此XML例如键值对:获得使用LINQ
<foo>
<add key="key1" Value="val1"/>
<add key="key2" Value="val2"/>
<add key="key3" Value="val3"/>
<foo/>
试试这个:
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();
嗨,这将不会编译。我得到:'System.Collections.Generic.IEnumerable
grr类型的第一个参数。没关系!使用System.Linq;需要do'h – raklos 2009-11-11 15:59:51
代替ToList();我会试图使用:.ToDictionary(item => item.Key,item => item.Value);就像OP的问题对我来说似乎更明显一样。 – Mike 2009-11-11 16:13:42
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...
我认为你的意思是属性而不是属性,元素只需要一个元素名称,而不是路径(无论如何,AFAIK)。 – 2009-11-11 15:53:35
我知道这只是一个例如,但 应该是 :) –
Mike
2009-11-11 16:15:27