How do I get multiple value of single xml element while deserializing xml to c# object?

295 views Asked by At

I am getting xml data from xml file to c# object which looks like below:

Xml:

<OrderItem>
          <OrderItemCode>1234</OrderItemCode>
          <ASIN>dfsdfcs</ASIN>
          <SKU>5MJ1L3</SKU>
          <ItemStatus>Unshipped</ItemStatus>
          <ProductName>xcv/ProductName>
          <Quantity>1</Quantity>
          <ItemPrice>
             <Component>
                        <Type>Principal</Type>
                        <Amount currency="CAD">7.99</Amount>
             </Component>
          </ItemPrice>
</OrderItem>

c# Model:

[XmlRootAttribute("OrderItem")]
public class OrderItem
    {
        [XmlElement("OrderItemCode")]
        public string OrderItemCode { get; set; }

        [XmlElement("ASIN")]
        public string Asin { get; set; }

        [XmlElement("SKU")]
        public string Sku { get; set; }

        [XmlElement("ItemStatus")]
        public string ItemStatus { get; set; }

        [XmlElement("ProductName")]
        public string ProductName { get; set; }

        [XmlElement("Quantity")]
        public long Quantity { get; set; }

        [XmlElement("ItemPrice")]
        public ItemPrice Item_Price { get; set; }

        [XmlElement("PriceDesignation")]
        public string PriceDesignation { get; set; }

        [XmlElement("Promotion")]
        public Promotion Promotion { get; set; }

    }

    public partial class ItemPrice
    {
        [XmlElementAttribute("Component")]
        public List<Component> Component { get; set; }
    }

    public partial class Component
    {
        [XmlElement("Type")]
        public string Type { get; set; }

        [XmlElement("Amount")]
        public Amount Amount { get; set; }
    }

    public partial class Amount
    {
        [XmlAttribute("currency")]
        public string Currencies { get; set; }

        [XmlAttribute("#text")]
        public string Price { get; set; }
    }

Deserialization:

 XmlSerializer serializer = new XmlSerializer(typeof(OrderItem));
 TextReader reader = new StreamReader(reportPath);
 OrderItem ordersListXML = (OrderItem)serializer.Deserialize(reader);

Here, I want to get the values of <Amount currency="CAD">7.99</Amount> by deserializing to c# object and I am able to get the value of attribute "currency" of Element <Amount currency="CAD">7.99</Amount> to "Currencies" property but unable to get the text "7.99" of Element <Amount currency="CAD">7.99</Amount> to "Price" property in my c# object after deserialization.

Can anyone help me to get the value !

1

There are 1 answers

1
Fruchtzwerg On

The XmlTextAttribute ([XmlText]) allows to deserialize the value of the entry to a field. So

<Amount currency="CAD">7.99</Amount>

can be desieralized to the class

public class Amount
{
    [XmlAttribute("currency")]
    public string Currencies { get; set; }

    [XmlText]
    public string Price { get; set; }
}