如何将嵌套元素的XML序列化为对象

时间:2011-07-21 10:21:41

标签: c# serialization windows-phone-7 xml-serialization

我有一个嵌套标签的xml,如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<questions>
  <question title="Which of these is a circle?" type="graphics">
    <text>Which of these is a circle?</text>
    <image src="shapes.png" />
    <Answer correct="true">
      <image src="circle.png"/> 
    </Answer>
    <Answer>
      <image src="square.png"/>
    </Answer>
  </question>
  <question title="Click on the circle" type="point">
    <image src="imageOfShapesWithTheAnswerAt200x150withASizeOf20x20.png"/>
    <Answer x="200" y="150" width="20" height="20" correct="true">Circle</Answer>
    <Answer x="100" y="150" width="20" height="20">NotCircle</Answer>
  </question>
  <question title="Trick question" type="text">
    <text>What was the colour of Duke Wellingtons white horse?</text>
    <image src="images.png" />
    <Answer correct="true">White</Answer>
    <Answer>Blue</Answer>
    <Answer>Black</Answer>
    <Answer>Red</Answer>
    <Answer>Green</Answer>
  </question>
</questions>

我如何将它序列化到这个类中?

    [XmlRoot("quiz")]
    public class Quiz
    {
        public class Question
        {
            public String QuestionText { get; set; }
            public String QuestionTitle { get; set; } // automatic getters and setters (nicer)
            public String QuestionImage { get; set; }

            [XmlArray]
            public List<Answer> Answers { get; set; }
        }

        public class Answer
        {
            public Boolean selected { get; set; }
            public Boolean correct { get; set; }

            [XmlElement("text")]
            public String text { get; set; }
            [XmlElement("image")]
            public String image { get; set; }
        }
    }

我已尝试使用序列化程序,因此对象中的[XmlElement][XmlRoot]但我正在努力使用它。

我已经看过许多序列化到xml但从xml到对象的序列化的例子。

修改

我找到了这个http://www.jonasjohn.de/snippets/csharp/xmlserializer-example.htm

的教程

1 个答案:

答案 0 :(得分:1)

    XDocument dok = XDocument.Load(Server.MapPath("XMLFile.xml"));
    XmlSerializer mySerializer = new XmlSerializer(typeof(Quiz));
    TextReader TW = new StringReader(dok.ToString());
    Quiz quizData= mySerializer.Deserialize(TW) as Quiz;

XmlSerializer的反序列化方法可以做到这一点。