Kristian Oye
Kristian Oye

Reputation: 1202

C# XmlSerializer: Deserializing child element text value

I am having trouble deserializing my XML data into the data structures I've defined. I don't have any control over the creation of the XML, but it is structured like:

<order id="123456">
   <userid>555</userid>
   <merchant id="111">SomeMerchant</merchant>
</order>

I get the top level attributes and simple element values okay, but the part that is giving me issues is assigning the value of a child element to a property in a child class. My data structures look something like:

public class OrderData
{
    [XmlElement("merchant", typeof(OrderMerchant))]
    public OrderMerchant Merchant { get; set; }

    [XmlAttribute("id")]
    public int OrderID { get; set; }
}

[Serializable]
public class OrderMerchant
{
    [XmlElement("merchant")]
    public string Name { get; set; }

    [XmlAttribute("id")]
    public int ID { get; set; }
}

My problem: When I deserialize the XML and get an object, I have a Merchant object with an ID of 111 but a null Name. How do I mark up my object so that the element text is assigned to the Name attribute? I tried using the element name and I've tried an XPath expression (but I don't even know if that's allowed in this context).

Upvotes: 2

Views: 1496

Answers (1)

Matt
Matt

Reputation: 621

You're telling the serializer to serialize an element merchant, and then the merchant object expects to receive another element "merchant" that will contain the name. Instead, mark the Name property with the attribute [XmlText] like so:

[Serializable]
public class OrderMerchant
{
    [XmlText]
    public string Name { get; set; }

    [XmlAttribute("id")]
    public int ID { get; set; }
}

And that should do it

Source

Upvotes: 3

Related Questions