Question

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.

Was it helpful?

Solution

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 using listItem in your select clause.

Your first line is returning an IEnumerable<XElement> of all nodes called "selectListItemDefinition". Your second line is just taking that IEnumerable<> and assigning the child elements called "item" it to variable named listItem.

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") with from listItem in xmlSList.Elements("item") and it should behave as you expect.

the full query would be:

var SListItem = 
                (
                    from xmlSList in xDoc.Descendants("selectListItemDefinition")
                    from listItem in xmlSList.Elements("item")
                    select new SelectListItem
                    {
                        Key = listItem .Attribute("key").Value,
                        Value = listItem .Attribute("value").Value
                    }
                ).ToList();

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 one from listItem in xDoc.Descendants("item") and you will get the same behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top