简体   繁体   English

C#XML反序列化包含属性和字符串列表的对象会产生一个空列表吗?

[英]C# XML Deserialize an Object containing an attribute and a list of string yields an empty list?

I am currently attempting to deserialize the following mesage: 我目前正在尝试反序列化以下消息:

<Message Id="1234">
    <Body>This</Body>
    <Body>Is</Body>
    <Body>Test</Body>
    <Body>Text</Body>
</Message>

Using the Following object: 使用以下对象:

public class Message
    {
        [XmlAttribute("Id")]
        public string Id { get; set; }

        [XmlArrayItem("Body")]
        public List<string> data { get; set; }

        public Message()
        {
            data = new List<string>();
        }
    }

The object successfully deserializes, but, the Message.data.Count is 0. I have tried adding an [XmlArray(ElementName="Message")] tag to data and still the string is empty. 该对象成功反序列化,但是Message.data.Count为0。我尝试向数据添加[XmlArray(ElementName="Message")]标记,但字符串仍然为空。

Thank you in advance! 先感谢您!

Change [XmlArrayItem("Body")] to [XmlElement("Body")] : [XmlArrayItem("Body")]更改为[XmlElement("Body")]

public class Message
{
    [XmlAttribute("Id")]
    public string Id { get; set; }

    [XmlElement("Body")]
    public List<string> data { get; set; }

    public Message()
    {
        data = new List<string>();
    }
}

This tells XmlSerializer that the list is to be formatted as a one-level sequence of elements rather than a two-level nested list. 这告诉XmlSerializer ,该列表将被格式化为元素的一级序列,而不是两级嵌套列表。

With XmlArrayItem , your XML would need to look like this: 使用XmlArrayItem ,您的XML需要看起来像这样:

<Message Id="1234">
    <data>
        <Body>This</Body>
        <Body>Is</Body>
        <Body>Test</Body>
        <Body>Text</Body>
    </data>
</Message>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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