LINQ to XML Вопрос для новичков:Возврат более одного результата

StackOverflow https://stackoverflow.com/questions/127258

  •  02-07-2019
  •  | 
  •  

Вопрос

Привет!

Я работаю над тем, чтобы разобраться в 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>

Я хотел бы получить значения атрибутов всех дочерних элементов Item элемента Group.Вот как выглядит мой запрос:

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).Я что-то пропустил?

Это было полезно?

Решение

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

Другие советы

Да, .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
                          }
              };

Вот форма метода запроса ответа:

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

Другая возможность — использовать предложение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, 
              };
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top