1

I'm getting XML in following format:

<Order>
    <OrderData>
        <OfferOrder></OfferOrder>
        <OfferOrder></OfferOrder>       
    </OrderData>
</Order>

Now when I'm Deserializng string orderxml containing the XML, It doesn't fill <OfferOrder> into my OrderData object.

XmlSerializer xmlserializer = new XmlSerializer((typeof(Order)));
using (TextReader reader = new StringReader(orderxml))
{
    order = (Order)xmlserializer.Deserialize(reader);
}

Classes:

public partial class Order
{
    private OrderOrderData orderDataField;

    public OrderOrderData OrderData
    {
        get
        {
            return this.orderDataField;
        }
        set
        {
            this.orderDataField = value;
        }
    }
}

public partial class OrderOrderData
{
    private OrderOrderDataOfferOrder[] offerOrderField;

    public OrderOrderDataOfferOrder[] OfferOrder
    {
        get
        {
            return this.offerOrderField;
        }
        set
        {
            this.offerOrderField = value;
        }
    }
}

Is something wrong with my classes?

Huma Ali
  • 1,759
  • 7
  • 40
  • 66

1 Answers1

2

There are some issues in your code. First you can make your properties to auto-implemented properties, that is omit the private backing-fields and write this instead:

public MyType MyProperty { get; set; }

Second you have to provide the names of the tags within the Xml to the serializer. In your case the names within the xml and those in your class-structure are equal, so you can omit the names also. However just for completeness:

public class Order
{
    [XmlElement("OrderData")
    public OrderOrderData OrderData { get; set; }
}

public class OrderOrderData
{
    [XmlElement("OfferOrder")
    public OrderOrderDataOfferOrder[] OfferOrder { get; set; }
}

The reason why it doesn´t work for you is that arrays are usually serialized with a nested element whose name in your case would be OfferOrders. Within that tag you have then the arrays elements. Usually it´s not wanted to have that further nesting, what you want instead is to flatten the elements of the array directly into your actual data-class. To do so add an XmlElement upfront your array-declaration with the name of the elements, in my code OfferOrder.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111