0

I have XML in the following format:

<LocationHierarchy>
    <Location name="Argentina" id="3">
        <Location name="Buenos Aires" id="4"/>
        <Location name="Cordoba" id="5"/>
        <Location name="Mendoza" id="6"/>
    </Location>
    ...
</LocationHierachy>

I have C# code that is deserializing this XML into the following classes:

[XmlRoot("LocationHierarchy")]
[Serializable]
public class LocationHierachy
{
    [XmlElement("Location", typeof(Country))]
    public List<Country> CountryList { get; set; }
}
public class Country
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlAttribute("id")]
    public int Id { get; set; }
    [XmlElement("Location", typeof(City))]
    public List<City> CityList { get; set; }
}
public class City
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlAttribute("id")]
    public int Id { get; set; }
    public int CountryId { get; set; }
}

I have this working fine. However, I would like to automatically set the CountryId of each City object to the Id of the Country object that contains its collection. Any thoughts as to how this could be achieved?

Citrus
  • 756
  • 1
  • 13
  • 26

1 Answers1

1
public class LocationHierachy
    {
        [XmlElement("Location", typeof(Country))]
        public List<Country> CountryList { get; set; }

        [OnDeserialized()]
        internal void OnDeserializedMethod(StreamingContext context)
        {
            foreach (var country in CountryList)
            {
                foreach (var city in country.CityList) {
                    city.CountryId = country.Id;
                }
            }
        }
    }
Ruslan
  • 126
  • 1
  • 3
  • Thanks for the suggestion Ruslan. However I've tried this and for some reason OnDeserializedMethod is never being called even though my deserialize code is calling the XmlSerializer.Deserialize method. I found this [related post](http://stackoverflow.com/questions/2897166/why-does-the-ondeserialization-not-fire-for-xml-deserialization) but it's a bit over my head so I'm not sure if I have the same issue as the OP. – Citrus Mar 18 '14 at 06:34