Phil
Phil

Reputation: 3994

When parsing XML with Linq, only one object gets fetched

I'm trying to populate an array with the following xml:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
   <data>
         <item>
              <date>1307018090</date>
              <price>10.4718867</price>
              <low>10.38100000</low>
              <high>10.49000000</high>
              <nicedate>14:39</nicedate>
         </item>
         <item>
              ...
         </item>

and so on

I'm using this Linq-query, which to me means that It'll create one object per :

var items = from item in doc.Element("data").Descendants()
                    select new Currency
                    {
                        Close = item.Element("price").Value.ToString(),
                        Date = item.Element("date").Value.ToString(),
                        Low = item.Element("low").Value.ToString(),
                        High = item.Element("high").Value.ToString(),
                        Time = item.Element("nicedate").Value.ToString()
                    };

And when I foreach through items, only one item gets selected. I'm not very used to Linq so I can't figure out how to properly construct this statement. Any suggestions?

Upvotes: 3

Views: 283

Answers (2)

Zruty
Zruty

Reputation: 8667

Descedants() method returns not only children, but also grand-children, grand-grand-children etc. So, the second tag that gets processed by LINQ is your first <item>'s <date> and it isn't processed (I think there should be an exception here, can't check at the moment).

Replace your Descedants() call to Elements("item"), as suggested by @DaveShaw

Upvotes: 1

DaveShaw
DaveShaw

Reputation: 52798

You need to start the Linq-Xml like so

var items = 
from item in 
doc.Element("data")
.Elements("item")

Upvotes: 6

Related Questions