反序列化字符串列表

时间:2014-03-26 22:52:13

标签: c# serialization

我正在尝试将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":[]}
]}

3 个答案:

答案 0 :(得分:1)

choices上添加这些属性:

[XmlArray]
[XmlArrayItem("choice")]
public Choices choices;

答案 1 :(得分:1)

我可能会超出这个问题的范围,但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;
    }
  }
}

答案 2 :(得分:0)

不应该是public List<string> choices;而不是public Choices choices;吗? 因为你对Question做了同样的事情(使用了一个数组)。

相关问题