开发者

Deserialize array into complex object

My XML message looks like:

<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>

How can I define the Order object to read from the reply array? My objects looks like:

[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")]
publi开发者_JAVA技巧c 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; }
}

In my case the orders should be in a separate element tag Orders. I want to read them from the reply element. Do you have any idea what to change at my objects XML attributes?


Change:

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

to:

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

well... strictly speaking I'd be inclined (I don't like settable lists) to use:

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

You also need a different root object:

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

Then this works:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜