XmlSerializer将数组属性isFixedSize设置为true

时间:2012-02-09 11:20:36

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

我正在使用XmlSerializer将某些XML反序列化为对象。我遇到的问题是,一旦我成功反序列化,我的一个属性是一个数组,属性isFixedSize设置为true。

我需要在稍后阶段手动添加到此数组,但不能。

这是我的对象(为简洁省略了其他属性)

namespace Omeda.Customer
{
    [Serializable()]
    [XmlRoot("Customer")]
    public class Customer : Error
    {
        [XmlArray("CustomerDemographics")]
        [XmlArrayItem("CustomerDemographic", typeof(CustomerDemographic))]
        public Omeda.Customer.CustomerDemographic[] CustomerDemographics { get; set; }
    }
}

这是我用来反序列化的方法(同样,为了简洁而省略了代码)

private T request_Get<T>(string url) where T : new()
{
    object returnObject = new T();

    try
    {
        var request = WebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "text/xml";
        request.Headers.Add("x-omeda-appid", this.API_KEY);
        request.Timeout = 50000;

        using (var response = request.GetResponse())
        {
            using (var responseStream = response.GetResponseStream())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                returnObject = (T)serializer.Deserialize(responseStream);
            }
        }
    }
    catch (WebException ex)
    {
        ...
    }

    return (T)returnObject;
}

返回此对象后,customer.CustomerDemographics.IsFixedSize将返回true。

有关如何解决这个问题的任何帮助,以及为什么会发生这种情况会很棒。

2 个答案:

答案 0 :(得分:1)

IsFixedSizealways true for an array。如果“需要在以后的某个阶段手动添加到此数组”,则不应使用数组;您可能应该使用List<CustomerDemographic>或其他可以增长的集合类型。

答案 1 :(得分:0)

您是否尝试将这些CustomerDemographic节点序列化为集合?

为此,请将typeof(CustomerDemographic)更改为typeof(List<CustomerDemographic>)。 那么你就可以改变那个系列中的物品了。或者:

var customer = ... //Customer instance
var list = new List<CustomerDemographic>(custeomr.CustomerDemographics);

// change list here: add, remove, replace

customer.CustomerDemographics = list.ToArray();

// continue using customer instance