【问题标题】:Set collection object property when deserializing XML in C#在 C# 中反序列化 XML 时设置集合对象属性
【发布时间】:2014-03-18 04:00:17
【问题描述】:

我有以下格式的 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>

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

[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# .net xml xml-serialization deserialization


    【解决方案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;
                    }
                }
            }
        }
    

    【讨论】:

    • 感谢鲁斯兰的建议。但是我已经尝试过了,出于某种原因,即使我的反序列化代码正在调用 XmlSerializer.Deserialize 方法,也永远不会调用 OnDeserializedMethod。我找到了这个related post,但它有点超出我的想象,所以我不确定我是否有与 OP 相同的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    相关资源
    最近更新 更多