Home >Backend Development >C++ >How Can I Deserialize an Object from a Serialized XML String in C#?

How Can I Deserialize an Object from a Serialized XML String in C#?

DDD
DDDOriginal
2024-12-26 14:39:17876browse

How Can I Deserialize an Object from a Serialized XML String in C#?

Deserializing an Object from a String

The provided method, SerializeObject, enables the serialization of objects to files. To retrieve the XML representation of the object as a string, a slight modification is required.

The solution involves replacing the StreamWriter with a StringWriter:

public static string SerializeObject<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());

    using(StringWriter textWriter = new StringWriter())
    {
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

The GetType() method is used in the XmlSerializer constructor to ensure that all possible subclasses of T are considered during serialization.

Unlike the usage of typeof(T), GetType() covers all subclasses, allowing the code to handle objects with inheritance. For more information and a concrete example where typeof(T) causes issues, refer to the following link: http://ideone.com/1Z5J1.

Additionally, it's worth noting that different versions of the .NET runtime may generate different exception messages when encountering errors with typeof(T).

The above is the detailed content of How Can I Deserialize an Object from a Serialized XML String in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn