Reputation: 65
Given the following xml:
<Location>
<LocationAttribute>
<OptionType>
<Code>02</Code>
<Description>RetailLocation</Description>
</OptionType>
<OptionCode>
<Code>03</Code>
<Description>Drop Box</Description>
</OptionCode>
</LocationAttribute>
<LocationAttribute>
<OptionType>
<Code>03</Code>
<Description>AdditionalServices</Description>
</OptionType>
<OptionCode>
<Category>06</Category>
<Code>031</Code>
<Name>**Find a drop off location**</Name>
</OptionCode>
<OptionCode>
<Category>07</Category>
<Code>001</Code>
<Name>**Ground**</Name>
</OptionCode>
<OptionCode>
<Category>07</Category>
<Code>002</Code>
<Name>**Air**</Name>
</OptionCode>
</LocationAttribute>
</Location>
How can I parse out the value of the Name attribute for each option code, when the OptionType's code is 3? I have been trying something like:
List<string> services = item.Descendants("LocationAttribute")
.Where(service => service.Element("OptionType").Value == "3")
.Select(service => service.Element("OptionCode").Element("Description").Value).ToList()
Upvotes: 1
Views: 59
Reputation: 32266
You need to do a SelectMany
. And inside Select
the Value
of the Name Element
for each of the OptionCode Elements
. Also you have to check the Value
of the Code Element
of the OptionType Element
and since it is a string
comparison you have to include the leading "0".
var services = item.Descendants("LocationAttribute")
.Where(loc => loc.Element("OptionType").Element("Code").Value == "03")
.SelectMany(loc => loc.Elements("OptionCode")
.Select(code => code.Element("Name").Value));
Upvotes: 3