0

I'm trying to use the contents of an XML file as the data source to a List of objects. The object looks like this:

public class QuestionData
{
public string QuestionName{get;set;}
public List<string> Answers{get;set;}
}

And here is my XML:

<?xml version="1.0" encoding="utf-8" ?>
<QuestionData>
    <Question>
        <QuestionName>Question 1</QuestionName>
        <Answers>
            <string>Answer 1</string>
            <string>Answer 2</string>
            <string>Answer 3</string>
            <string>Answer 4</string>
        </Answers>
    </Question>
    <Question>
        <QuestionName>Question 2</QuestionName>
        <Answers>
            <string>Answer 1</string>
            <string>Answer 2</string>
            <string>Answer 3</string>
        </Answers>
    </Question>
</QuestionData>

The code I'm using to try and do this is:

var xml = XDocument.Load ("C:\temp\xmlfile.xml");

List<QuestionData> questionData = xml.Root.Elements("Question").Select 
(q => new QuestionData {
  QuestionName = q.Element ("QuestionName").Value, 
  Answers = new List<string> { 
    q.Element ("Answers").Value }
}).ToList ();

The code compiles, but I'm not getting any data from the XML. I looped through questionData to try and display the information to the console but it was empty.

0

1 Answer 1

4
List<QuestionData> questionData =
    xml.Root
       .Elements("Question")
       .Select(q => new QuestionData
                     {
                         QuestionName = (string)q.Element("QuestionName"),
                         Answers = q.Element("Answers")
                                    .Elements("string")
                                    .Select(s => (string)s)
                                    .ToList()
                     }).ToList();

I used (string)XElement cast instead of XElement.Value property because it doesn't throw NullReferenceException when element is null.

Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to include a boolean value as well for each Answer item that is brought in from the xml? I want to have the default selection state for each answer to be false so I was thinking maybe to change the Answers property in the QuestionData class to public List<Tuple<string, bool>> Nominees { get; set; } and then trying something like Answers = new Tuple<string,bool> (q.Element("Answers").Elements("string").Select(s => (string)s), false).ToList() but I'm receiving an implicit conversion error with that code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.