简体   繁体   中英

XML de-serialization of an array

I have such an xml

<?xml version="1.0" ?>
<response>
    <id-number>2979183</id-number>
    <differentiator-question>
        <prompt>How old are you?</prompt>
        <type>age.range</type>
        <answer>29 - 38</answer>
        <answer>39 - 48</answer>
        <answer>49 - 58</answer>
        <answer>59 - 68</answer>
        <answer>None of the above</answer>
    </differentiator-question>
    <error>Invalid username and password</error>
</response>

which I try to de-serialize using the built in serialization mechanism in .NET. Created such a class

[XmlRoot("response")]
public class IdologyAnswerMapping
{
    [XmlElement("id-number")]
    public string IdNumber { get; set; }    
    public class DifferentiatorQuestionType
    {
        [XmlElement("prompt")]
        public string Prompt { get; set; }

        [XmlElement("type")]
        public string Type { get; set; }

        [XmlArray("answer")]
        public string[] Answers { get; set; }
    }

    [XmlElement("differentiator-question")]
    public DifferentiatorQuestionType DifferentiatorQuestion { get; set; }

    public static IdologyAnswerMapping FromXml(string xml)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(IdologyAnswerMapping));
        IdologyAnswerMapping answer = (IdologyAnswerMapping)serializer.Deserialize(new StringReader(xml));
        return answer;
    }
}

But the Answers array is of zero size. How do I place all the <answer /> tags into Answers array?

Thank you.

Use XmlElement instead of XmlArray

[XmlElement("answer")]
public string[] Answers { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM