deserializing xml to generic collection problem

DimkaNewtown

Freshman
Joined
Jan 21, 2003
Messages
43
Location
New York City
I have a set of data returning from a stored proc that needs to be deserialized to a generic collection, and I'm stumped.

the xml is of the form
Code:
<Countries>
  <Country countrycode="" countryname="">
  <Country countrycode="" countryname="">
<Countries>

the class looks like this
Code:
   [Serializable]
    public class Country
    {
        string _code;
        string _name;

        public Country()
        {
            _code = String.Empty;
            _name = String.Empty;
        }
        public Country( string CountryCode, string CountryName )
        {
            _code = CountryCode;
            _name = CountryName;
        }

        public string CountryCode
        {
            get { return _code; }
            set { _code = value; }
        }

        public string CountryName
        {
            get { return _name; }
            set { _name = value; }
        }
    }

now I can deserialize a single object correctly to a class but with a generic collection the code doesn't work, i get a "<Countries xmlns=''> was not expected." error.

Any ideas? Of course I could load the xmlDocument and go throw each Country element in a loop and serialized them one by one while adding them to a generic collection but that kinda defeats the purpose, doesn't it? :rolleyes:

Edit: forgot deserialization code
Code:
      public static T DeserializeObject<T>(string targetXml)
        {
            XmlSerializer s = null;
            StringReader sr = null;
            XmlTextReader xtr = null;
            try
            {
                sr = new StringReader(targetXml);
                xtr = new XmlTextReader(sr);
                s = new XmlSerializer(typeof(T));
                

                if (s.CanDeserialize(xtr))
                    return (T)s.Deserialize(xtr);
                else
                    throw new Exception();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                s = null;
                if (sr != null)
                    sr.Close();
                sr = null;
                if (xtr != null)
                    xtr.Close();
                xtr = null;
            }
        }
 
Last edited:
Back
Top