2011-07-19 77 views
0

我有一个XML文件,它看起来像这样你如何从xml读取嵌套对象?

<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> ... 

我设法弄清楚如何使用该对象的公共方法来读取属性和值到属性,但如何将我得到一个“问题”的对象,包含‘答案’的对象,这将是最好只比使用LINQ到XML序列化

这是使用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我如何去将另一个节点序列化为另一个对象,比如说我有一个“问题”中的“答案”对象列表?

回答

1

您可以使用序列化,但如果你想拥有这样做的完全custimizable方式,我会推荐这:

问题类:

public static Question FromXmlElement(XElement el) 
{ 
    return new Question 
    { 
     Text = el.Element("Text").Value, 
     Answers = el.Elements("Answer").Select(a=>a.Value); 
    }; 
} 

,当你想读:

var xdoc = XDocument.Parse(xml); 
var questions = xdoc.Element("Questions").Elements("Question") 
      .Select(e=> Question.FromXmlElement(e)); 

从FromXmlElement里面你可以调用另一个复杂类型的方法相同,如果你的类具有复杂类型的属性等。

+0

然后我可以从第二部分访问“答案”对象? –

+0

是的,从FromXmlElement中可以得到有关xml元素(el)中单个问题的所有信息。 –

+0

我想将它序列化为可重复的“问题”对象,这些对象内部具有无法回答的“应答”对象。因为我正在使用一个无数的洗牌课来洗牌。 –