我正在尝试将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;
};去序列化。
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":[]}
]}发布于 2014-03-26 22:55:32
在choices上添加这些属性
[XmlArray]
[XmlArrayItem("choice")]
public Choices choices;发布于 2014-03-26 22:57:32
我可能超出了这个问题的范围,但是VS2013有一个非常酷的特性:Edit-->Paste Special--> Paste XML As Classes
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class survey
{
private surveyQuestion[] questionField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("question")]
public surveyQuestion[] question
{
get
{
return this.questionField;
}
set
{
this.questionField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class surveyQuestion
{
private string typeField;
private string textField;
private string[] choicesField;
/// <remarks/>
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
/// <remarks/>
public string text
{
get
{
return this.textField;
}
set
{
this.textField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("choice", IsNullable = false)]
public string[] choices
{
get
{
return this.choicesField;
}
set
{
this.choicesField = value;
}
}
}发布于 2014-03-26 22:57:05
不是应该是public List<string> choices;而不是public Choices choices;吗?因为您对Question也做了同样的操作(使用了数组)。
https://stackoverflow.com/questions/22674722
复制相似问题