我試圖將XML反序列化爲C#對象。我已經嘗試了很多方案,但不能爲我的生活獲取反序列化來獲取choices
。請參見下面的代碼...反序列化字符串列表
的XML ...
@"<?xml version=""1.0"" encoding=""UTF-8""?>
<survey>
<question>
<type>multiple-choice</type>
<text>Question 1</text>
<choices>
<choice>Answer A</choice>
<choice>Answer B</choice>
<choice>Answer C</choice>
</choices>
</question>
<question>
<type>multiple-choice</type>
<text>Question 2</text>
<choices>
<choice>Answer a</choice>
<choice>Answer b</choice>
</choices>
</question>
</survey>
我的C#模型...
[XmlType("question")]
public struct Question
{
public String type;
public String text;
public Choices choices;
};
public class Choices : List<String> { };
[XmlType("survey")]
public class Survey
{
[XmlElement(ElementName = "question")]
public Question[] Questions;
};
Deserialisation ...
using System.Xml.Serialization;
Survey survey;
XmlSerializer serializer = new XmlSerializer(typeof(Survey));
survey = (Survey)serializer.Deserialize(reader);
結果顯示爲JSON ...
{"Questions":[
{"type":"multiple-choice","text":"Question 1","choices":[]},
{"type":"multiple-choice","text":"Question 2","choices":[]}
]}
我猜應該是'公開名單選擇;'而不是'公共選擇的選擇;'(看我的答案)。另外,「選擇」類不應該是「列表」的孩子。 –
@MarkusSafar,謝謝,是的,我已經嘗試過以及'public String []選擇;'但是它不能讓它工作,這在工作中遇到問題時很奇怪。但是,當我添加托馬斯的回答 – spiderplant0