Jump to content
Xtreme .Net Talk

Recommended Posts

Posted (edited)

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

<Countries>
 <Country countrycode="" countryname="">
 <Country countrycode="" countryname="">
<Countries>

 

the class looks like this


  [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

     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;
           }
       }

Edited by DimkaNewtown

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...