Search code examples
c#linqxelement

Looping through XElement items


I've the following XML:

<ArrayOfCustomerOrderExportInfo>
<CustomerOrderExportInfo>
<ID>168</ID>
<CustomerOrderLines>
<CustomerOrderExportInfo>
<Amount>1522</Amount>
</CustomerOrderExportInfo>
<CustomerOrderExportInfo>
<Amount>1522</Amount>
</CustomerOrderExportInfo>
...
</CustomerOrderLines>
</CustomerOrderExportInfo>
</ArrayOfCustomerOrderExportInfo>

I loop through this like this:

using System.Linq
using System.XML.Linq

Stream xmlUpload = <file>

var customerOrders = from co in 
                      XElement.Load(xmlUpload).Eelements("CustomerOrderExportInfo")
select co;

xmlUpload.Close
foreach(var orderXML in customerOrders)
{
    int orderID = Convert.ToInt32(orderXML.Element("ID").Value);

}

This gives me ID 168 fine.

Now I want to loop through the CustomerOrderExportInfo items in the existing foreach loop and then it fails.

I've tried

var customerOrderLine = orderXML.Descendants("CustomerOrderExportInfo") 

but this gives an empty collection. Also various kind of orderXML.Nodes() but always empty collection.

Pointers and help appreciated

Kind regards

Jeroen


Solution

  • Funny,

    if i try to place it in a variable it fails:

    var test = orderXML.Descendants("CustomerOrderLineExportInfo");
    

    but like so:

    foreach(var orderLine in orderXML.Descendants("CustomerOrderLineExportInfo"))
    {
        ...
    }
    

    i can loop through the records

    Jeroen