I am attempting to get a Select List from an XML string...
<?xml version="1.0" encoding="utf-8"?>
<selectListItemDefinition id="UPMCTypes">
  <item key="bla1" value="bla" />
  <item key="bla2" value="bla" />
  <item key="bla3" value="bla" />
  <item key="bla4" value="bla" />
  <item key="bla5" value="bla" />
  <item key="bla6" value="bla" />
  <item key="bla7" value="bla" />
  <item key="bla8" value="bla" />
  <item key="bla9" value="bla" />
  <item key="bla10" value="bla" />
  <item key="bla11" value="bla" />
</selectListItemDefinition>
That would be the XML string that I am trying to turn into a SelectList Here is how I am trying to do it...
List<SelectListItem> SListItem =
(
    from xmlSList in xDoc.Descendants("selectListItemDefinition")
    let listItem = xmlSList.Elements("item")
    select new SelectListItem
    {
        Key = xmlSList.Attribute("key").Value,
        Value = xmlSList.Attribute("value").Value
    }
).ToList();
This only gets the first Key-Value one for me.
Key    "blah1"  string
Value  "blah"   string
Now I think it's because I am only getting one Element here? But I am not sure what I would do to get this right.
                        
I think you have a problem in your query, as you should be getting an exception.
You are trying to select the attributes "key" and "value" of
<selectListItemDefinition>, but they don't exist. And you are not actually usinglistItemin your select clause.Your first line is returning an
IEnumerable<XElement>of all nodes called "selectListItemDefinition". Your second line is just taking thatIEnumerable<>and assigning the child elements called "item" it to variable namedlistItem.When you should be doing is a second query to iterate over the
<selectListItemDefinition>elements instead of assigning it.So replace
let listItem = xmlSList.Elements("item")withfrom listItem in xmlSList.Elements("item")and it should behave as you expect.the full query would be:
And if you are 100% certain that the only elements called
<item>in your XML document are the ones you want, you can replace the first and second lines with a single onefrom listItem in xDoc.Descendants("item")and you will get the same behavior.