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

时间:2014-03-18 04:00:18

标签: c# .net xml xml-serialization deserialization

我有以下格式的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。有关如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分: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;
                }
            }
        }
    }