我想,以反映我的對象結構的XML樹,但我很LINQ to XML中一個初學者試圖使用LINQ來解析XML樹XML(C#)
我有以下結構的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; }
}
...我有建立以下(錯誤)Linq查詢:
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();
當然這樣我每次都會把所有問題中的所有問題都添加到每個列表中。 如何解決這個問題?我可以想象這很簡單,但我不知道:)
先謝謝您!
使用`LINQ`解析XML有沒有優於使用`XmlDocument`? – Meysam 2012-01-27 05:17:24