SyntaxTerror
SyntaxTerror

Reputation: 23

Reading list of ints from XML file using Linq

I have a following XML file:

<Application>
<Items>
    <Item>
      <Id>0</Id>
      <StartDate>0001-01-11T00:00:00</StartDate>
      <EndDate>0001-01-30T00:00:00</EndDate>
      <ItemType>0</ItemType>
      <Comments>fgdfg</Comments>
      <SelectedIds>
        <Id>108</Id>
        <Id>110</Id>
        <Id>111</Id>
      </SelectedIds>
    </Item>
</Items>

I want to read list of Items, which represent my CustomClass. I'm using following linq query:

CustomClassList = new ObservableCollection<CustomClass>((from r in xml.Descendants("Application").Descendants("Items").Descendants("Item")
select (new CustomClass()
{
    Id = (int)r.Element("Id"),
    StartDate= DateTime.Parse(r.Element("StartDate").Value),
    EndDate = DateTime.Parse(r.Element("EndDate").Value),
    ItemType = (ItemType)byte.Parse(r.Element("ItemType").Value),
    Comment = r.Element("Comment").Value,
    SelectedIds = new List<int>((from p in xml.Descendants("Application").Descendants("Items").Descendants("Item").Descendants("SelectedIds")
                                 select (int)p.Element("Id")).ToList())

})).ToList());

It works fine, except the fact, that SelectedIds contains only first Id from XML instead of all Ids.

Upvotes: 0

Views: 90

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726839

You should use r as the starting point for your sub-list, instead of the "global" root xml:

SelectedIds = r.Descendants("SelectedIds")
               .SelectMany(p => p.Descendants("Id").Select(x => (int)x))
               .ToList()

Upvotes: 1

Related Questions