I have an xml file that looks something like this
<questions>
<question>
<text>What color is an orange?</text>
<answer>blue</answer>
<answer>yellow</answer>
<answer>orange</answer>
</question>
<question>
<text>What color is a banana?</text> ...
I’ve managed to figure out how to read attributes and values into the properties using the public methods for the object, but how would i get a “Question” object that would contain “Answer” objects, would it be better to just serialize than use linq-to-xml
This is using linq:
var data = from query in questionData.Descendants("question")
select new Quiz.Question
{
QuestionTitle = (string)query.Attribute("title"),
QuestionText = query.Element("text") != null ? query.Element("text").Value.Trim() : string.Empty,
QuestionImage = query.Element("image") != null ? query.Element("image").Attribute("src").Value : string.Empty
…
in linq how do I go about serializing another node as another object, say i have a list of “answer” object in “question”?
You can use serialization for this, but if you want to have a totally custimizable way of doing this I would recommend this:
In Question class:
and when you want to read:
from inside the FromXmlElement you can call same method of another complex type if your class has a property of a complex type and so on.