将数组反序列化为复杂对象

时间:2011-01-25 10:15:25

标签: c# .net xml xml-serialization xsd

我的XML消息如下:

<msg>
    <reply userid="sales" requestid="2" index="1" pagesize="1000" total="1" type="order">
        <order id="12db8625cd4-000" owner="sales">
            <qty size="1" working="0"/>
            <price limit="0.0"/>
        </order>            
        <order id="12db8636344-000" owner="sales">
            <qty size="1000" working="0"/>
            <price limit="0.0"/>
        </order>
    </reply>
</msg>

如何定义Order对象以从回复数组中读取?我的对象看起来像:

[XmlRootAttribute("reply")]
public class MessageReply
{
    [XmlAttribute("userid")]
    public string UserId { get; set; }

    [XmlAttribute("requestid")]
    public string RequestId { get; set; }

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

    [XmlArrayItem(typeof(Order))]
    public List<Order> Orders { get; set; }
}

[XmlRootAttribute("order")]
public class Order
{
    [XmlAttribute("id")]
    public string Id { get; set; }
    [XmlAttribute("owner")]
    public string Owner { get; set;}
    [XmlAttribute("assignee")]
    public string Assignee { get; set; }
    [XmlAttribute("instrumentid")]
    public string InstrumentId { get; set; }
    [XmlAttribute("side")]
    public string Side { get; set;}
    [XmlAttribute("type")]
    public string Type { get; set; }
}

在我的情况下,订单应该在单独的元素标签订单中。我想从reply元素中读取它们。你知道在我的对象XML属性上要改变什么吗?

1 个答案:

答案 0 :(得分:5)

变化:

[XmlArrayItem(typeof(Order))]
public List<Order> Orders { get; set; }

为:

[XmlElement("order")]
public List<Order> Orders { get; set; }

嗯... 严格说我倾向于(我不喜欢可设置的列表)使用:

private List<Order> orders;
[XmlElement("order")]
public List<Order> Orders {get{ return orders ?? (orders = new List<Order>());}}

您还需要一个不同的根对象:

[XmlRoot("msg")]
public class Message
{
    [XmlElement("reply")]
    public MessageReply Reply { get; set; }
}

然后这个有效:

var ser = new XmlSerializer(typeof(Message));
MessageReply reply;
using(var reader = new StringReader(xml))
{
    reply = ((Message)ser.Deserialize(reader)).Reply;
}