Home > database >  Serialize XML text to an object
Serialize XML text to an object

Time:08-16

I have in my database many objects that have been serialized to XML format. Now, I need to get those XML's back to objects again. What would be the best way to do this, using as little code as possible.

CodePudding user response:

I believe the best way is to build a generic method to convert any object. But obviously you need to be in control of which object will be converted from the returned XML.

public T SerializeStringToObject(string XML) 
    {

        T convertedObject;

        try
        {   
            System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(T));
                                                    
            using (System.IO.StringReader objetoXML = new System.IO.StringReader(XML))
            {
                convertedObject = (T)xml.Deserialize(objetoXML);
                objetoXML.Close();
            }

            return convertedObject;

        }
        catch (Exception ex)
        {
            throw ex;
        }

    }
  •  Tags:  
  • c#
  • Related