在c#中反序列化XML时设置集合对象属性

本文关键字:设置 集合 对象 属性 XML 反序列化 | 更新日期: 2023-09-27 17:50:39

我有以下格式的XML:

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

我有c#代码将这个XML反序列化为以下类:

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

我有这个工作良好。但是,我想将每个City对象的CountryId自动设置为包含其集合的Country对象的Id。对于如何实现这一点有什么想法吗?

在c#中反序列化XML时设置集合对象属性

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