简体   繁体   中英

Serialize XML text to an object

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.

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM