alduin
alduin

Reputation: 317

C# - using Linq to XML to populate list of objects

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.

Upvotes: 0

Views: 4550

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

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.

Upvotes: 4

Related Questions