Scottie
Scottie

Reputation: 11308

C# XML Deserialize object is empty

I am attempting to deserialize an XML string to an object.

The object is:

[Serializable]
public class THIRD_PARTY_CONFIRMATION
{
    public string thirdPartyId { get; set; }
}

and the code I am trying to run is:

var response = "<?xml version='1.0' encoding='UTF-8' ?><THIRD_PARTY_CONFIRMATION thirdPartyId = \"3984000\" />";
using (var stream = new StringReader(response))
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(THIRD_PARTY_CONFIRMATION));
    var temp = (THIRD_PARTY_CONFIRMATION)xmlSerializer.Deserialize(stream);
}

If I inspect temp in Visual Studio, thirdPartyId is null. What am I doing wrong?

Upvotes: 0

Views: 424

Answers (1)

Thomas Lindvall
Thomas Lindvall

Reputation: 599

You need to add the property XmlAttribute to the thirdPartyId

[Serializable]
public class THIRD_PARTY_CONFIRMATION
{
    [XmlAttribute]
    public string thirdPartyId { get; set; }
}

otherwise it'll start looking for a value of the element and not an attribute.

Upvotes: 3

Related Questions