Caveman's Blog

My commitment to learning.

XML deserialization: There is an error in XML document (4, 6).

leave a comment »


Deserialization is the reconstruction of an object from an object store (XML or binary file). I was trying to deserialize an object that was stored in an XML file when the following exception was thrown:

System.InvalidOperationException: There is an error in XML document (4, 6).

After some debugging I was able to see that during deserialization, I was able to figure out that a list object that is being exposed as a property in one my classes is the source of the issue.

    public class FavCity: List<string>
    {
    }

    public class Profile
    {
        private FavCities _FavCities;
        [XmlArrayItem("FavCity")]
        public FavCities FavoriteCities
        {
            get
            {
                return _FavCities;
            }
            set
            {
                if (value != null && value.Count > 0)
                    _FavCities = value;
                else
                    throw new ArgumentException("FavCities null exception.");
            }
        }
    }

The fix to this issue is to ensure that the get method of the FavoriteCities property is returning a non-NULL value at all times. So the new code for the property looks like this:

        private FavCities _FavCities;
        [XmlArrayItem("FavCity")]
        public FavCities FavoriteCities
        {
            get
            {
                if (_FavCities == null)
                    _FavCities = new FavCities();

                return _FavCities;
            }
            set
            {
                if (value != null && value.Count > 0)
                    _FavCities = value;
                else
                    throw new ArgumentException("FavCities null exception.");
            }
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: