Removing array deserialization into a complex object

My XML message looks like this:

<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 an Order object to read from an array of responses? My objects look like this:

[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; }
}

In my case, orders should be in a separate tag for order tags. I want to read them from the response element. Do you have any ideas what to change XML attributes in my objects?

+3
source share
1 answer

Edit:

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

at

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

well ... strictly speaking, I would be inclined (I don't like custom lists):

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

You also need another root object:

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

Then it works:

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

Source: https://habr.com/ru/post/1787648/


All Articles