What I have is an XML we receive from a web service which represents a list of questions. The questions are broken down by type which indicates how they should be displayed on the web. For instance:
<step id="109025">
<stepinf enabled="Yes" errors="0" id="First Name" mandatory="Yes" name="sti_115511" type="FIL">
<field_label>First Name</field_label>
<screen_value></screen_value>
</stepinf>
<stepinf enabled="Yes" errors="0" id="Last Name" mandatory="Yes" name="sti_115513" type="FIL">
<field_label>Last Name</field_label>
<screen_value></screen_value>
</stepinf>
<stepinf enabled="Yes" errors="0" id="State" mandatory="Yes" name="sti_109257" type="STE">
<field_label>State</field_label>
<screen_value></screen_value>
<options_list>
<option label="AK">AK - Alaska</option>
<option label="AL">AL - Alabama</option>
<option label="AR">AR - Arkansas</option>
<option label="AS">AS - American Samoa (Terr.)</option>
<option label="AZ">AZ 开发者_StackOverflow- Arizona</option>
...
</options_list>
</stepinf>
</step>
The type "STE" indicates that it will display on the web as a select box.
I am populating a List<> of a custom type I created by doing the following:
var stepinfList = (from stepinf in xdoc.Descendants("stepinf")
select new Question
{
TextID = stepinf.Attribute("id").Value,
Type = stepinf.Attribute("type").Value,
Name = stepinf.Attribute("name").Value,
Label = stepinf.Element("field_label").Value,
Required = stepinf.Attribute("mandatory").Value,
ErrorCount = int.Parse(stepinf.Attribute("errors").Value)
}).ToList();
Where I am getting lost at is I have no idea how to get the option sub-elements into my results. I tried creating a property in the Question type named Options which I defined as an IDictionary and then utilized a sub-select in my LINQ query and the ToDictionary extension.
Options = (from option in xdoc.Element("options_list").Elements("option")
select option)
.ToDictionary(x => x.Attribute("label").Value, x => x.Value)
This didn't work as I think it bombs on the stepinf records that do not have child option_list elements. Anyway, I get "Object reference not set to an instance of an object" on the LINQ statement when I run the page.
I'm afraid this is above my current LINQ skill set so any help would be greatly appreciated.
This didn't work as I think it bombs on the stepinf records that do not have child option_list elements.
Your assessment is correct, so you need to check whether option_list
exists before querying it. Check if it's null and return the dictionary or return null accordingly.
Try this:
Options = stepinf.Element("options_list") == null ? null :
stepinf.Element("options_list").Elements("option")
.ToDictionary(x => x.Attribute("label").Value, x => x.Value)
精彩评论