我想在我的对象结构中反映
XML树,但我是LINQ to
XML的初学者
我有一个XML结构如下:
<questions> <question id="q1"> <number>1</number> <text>some text11</text> <answers> <answer> <v>some text11</v> </answer> <answer> <v>some text11</v> </answer> </answers> </question> <question id="q2"> <number>2</number> <text>some text2</text> <answers> <answer> <v>some text22</v> </answer> <answer> <v>some text22</v> </answer> </answers> </question> <question id="q3"> <number>3</number> <text>some text3</text> <answers> <answer> <v>some text33</v> </answer> <answer> <v>some text33</v> </answer> <answer> <v>some text33</v> <addDescription>some text333</addDescription> <textBox/> </answer> </answers> </question> </questions>
……我有以下课程:
public class Question { public string text { get; set; } public IList<Anwser> anwsers = new List<Anwser>(); } public class Anwser { public string content { get; set; } }
List<Question> questions = (from xml in xdoc.Element("survey").Elements("questions").Elements("question") select new Question() { text = xml.Element("text").Value,anwsers = (from anwsers in xdoc.Element("survey").Elements("questions").Elements("question").Elements( "answers").Elements( "answer") select new Anwser() { content = anwsers.Element("v").Value } ).ToList() }).ToList();
当然,这样每次所有问题的所有问题都会添加到每个列表中.
怎么解决这个?我可以想象这很简单,但我不知道:)
先感谢您!
您的代码无效,因为您要回复所有答案元素,因为您没有根据它们的问题限制它们.您可以添加此限制,或者根据文档添加子查询,而不是基于问题元素本身创建子查询.
原文链接:https://www.f2er.com/xml/292069.htmlList<Question> questions = (from question in xdoc.Element("survey").Element("questions").Elements("question") select new Question { text = question.Element("text").Value,anwsers = (from answer in question.Element("answers").Elements("answer") select new Anwser { content = answer.Element("v").Value }).ToList() }).ToList();