简体   繁体   中英

Set collection object property when deserializing XML in C#

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?

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;
                }
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM