Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to XML Newbie Question: Returning More Than One Result

Tags:

c#

linq-to-xml

Greetings!

I'm working on wrapping my head around LINQ. If I had some XML such as this loaded into an XDocument object:

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

I'd like to get the attribute values of all of the Item child elements of a Group element. Here's what my query looks like:

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

The query works, but if for example the groupName variable contains "GroupB", only one result (the first Item element) is returned instead of three. Am I missing something?

like image 648
Bullines Avatar asked Jan 24 '23 02:01

Bullines


1 Answers

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);
}
like image 172
aku Avatar answered Feb 20 '23 20:02

aku