LINQ to XML新手问题:返回多个结果
时间:2020-03-06 14:39:46 来源:igfitidea点击:
你好!
我正在努力将自己的头缠在LINQ上。如果我将这样的XML加载到XDocument对象中:
<Root> <GroupA> <Item attrib1="aaa" attrib2="000" attrib3="true" /> </GroupA> <GroupB> <Item attrib1="bbb" attrib2="111" attrib3="true" /> <Item attrib1="ccc" attrib2="222" attrib3="false" /> <Item attrib1="ddd" attrib2="333" attrib3="true" /> </GroupB> <GroupC> <Item attrib1="eee" attrib2="444" attrib3="true" /> <Item attrib1="fff" attrib2="555" attrib3="true" /> </GroupC> </Root>
我想获取Group元素的所有Item子元素的属性值。这是我的查询内容:
var results = from thegroup in l_theDoc.Elements("Root").Elements(groupName) select new { attrib1_val = thegroup.Element("Item").Attribute("attrib1").Value, attrib2_val = thegroup.Element("Item").Attribute("attrib2").Value, };
该查询有效,但是例如,如果groupName变量包含" GroupB",则仅返回一个结果(第一个Item元素),而不是三个。我想念什么吗?
解决方案
是的.Element()仅返回第一个匹配的元素。我们需要.Elements(),并且需要重新编写查询:
var results = from group in l_theDoc.Root.Elements(groupName) select new { items = from i in group.Elements("Item") select new { attrib1_val = i.Attribute("attrib1").Value, attrib2_val = i.Attribute("attrib2").Value } };
XElement e = XElement.Parse(testStr); string groupName = "GroupB"; var items = from g in e.Elements(groupName) from i in g.Elements("Item") select new { attr1 = (string)i.Attribute("attrib1"), attr2 = (string)i.Attribute("attrib2") }; foreach (var item in items) { Console.WriteLine(item.attr1 + ":" + item.attr2); }
另一种可能性是使用where子句:
var groupName = "GroupB"; var results = from theitem in doc.Descendants("Item") where theitem.Parent.Name == groupName select new { attrib1_val = theitem.Attribute("attrib1").Value, attrib2_val = theitem.Attribute("attrib2").Value, };
这是答案的查询方法形式:
var items = e.Elements("GroupB") .SelectMany(g => g.Elements("Item")) .Select(i => new { attr1 = i.Attribute("attrib1").Value, attr2 = i.Attribute("attrib2").Value, attr3 = i.Attribute("attrib3").Value } ) .ToList()