I have a following xml with duplicate nodes named(“address”) and I need to deserialize these “address” nodes to one object:
<dealer id="8569" ed="0">
<name hide="0">some name</name>
<url>http://www.some.com</url>
<address hide="0" />
<address>
<line1>text1</line1>
<line2>text2</line2>
<line3>text3</line3>
<town>Town</town>
<postcode>Postcode</postcode>
</address>
</dealer>
I need to deserialize it to the following class:
public class Dealer
{
public Dealer()
{
_address = new Address();
}
[XmlAttribute("id")]
public long Id { get; set; }
[XmlElement("name")]
public string Name{ get; set; }
[XmlElement("url")]
public string Url{ get; set; }
[XmlElement("address")]
public Address Address{ get; set; }
}
public class Address
{
[XmlElement("line1")]
public string Line1{ get; set; }
[XmlElement("line2")]
public string Line2 { get; set; }
[XmlElement("line3")]
public string Line3 { get; set; }
[XmlElement("county")]
public string County{ get; set; }
[XmlElement("town")]
public string Town{ get; set; }
[XmlElement("postcode")]
public string Postcode{ get; set; }
}
When this xml is deserialized to above class, it always gets the first “address” node, however, I need the second node to be picked up. How can I do this?
Short of changing your XML schema, all I can think of is having your
Dealerclass implementIXmlSerializableand implement the associatedReadXmlmethod to use the desired xml node. http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.readxml.aspxOther than that, you could alter your
Dealer.Addressto be a collection/array ofAddressobjects which are compatible to both representations then after deserialization ignore/remove the empty address from the collection.