Pregunta para principiantes de LINQ a XML:Devolver más de un resultado
-
02-07-2019 - |
Pregunta
¡Saludos!
Estoy trabajando para comprender LINQ.Si tuviera algún XML como este cargado en un objeto 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>
Me gustaría obtener los valores de los atributos de todos los elementos secundarios del elemento de un elemento de grupo.Así es como se ve mi consulta:
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,
};
La consulta funciona, pero si, por ejemplo, la variable groupName contiene "GrupoB", solo se devuelve un resultado (el primer elemento Item) en lugar de tres.¿Me estoy perdiendo de algo?
Solución
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);
}
Otros consejos
Sí, .Element() solo devuelve el primer elemento coincidente.Quieres .Elements() y necesitas reescribir tu consulta un poco:
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
}
};
Aquí está la forma del método de consulta de la respuesta:
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()
Otra posibilidad es utilizar una cláusula donde:
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,
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow