Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize from string instead TextReader

People also ask

How to deserialize string to XML in c#?

string operationXML = webRequest. getJSON(args[1], args[2], pollURL); var serializer = new XmlSerializer(typeof(StatusDocumentItem)); StatusDocumentItem result; using (TextReader reader = new StringReader(operationXML)) { result = (StatusDocumentItem)serializer. Deserialize(reader); } Console. WriteLine(result.

What is the correct way of using XML Deserialization?

The most common usage of XML serialization is when XML data is sent from the database server to the client. Implicit serialization is the preferred method in most cases because it is simpler to code, and sending XML data to the client allows the Db2 client to handle the XML data properly.

How does deserialize work in C#?

Deserialization is the process of reconstructing an object from a previously serialized sequence of bytes. It allows us to recover the object whenever it is required. It is the reverse process of serialization. Deserialize() method of BinaryFormatter class is used for deserialization from binary stream.


public static string XmlSerializeToString(this object objectInstance)
{
    var serializer = new XmlSerializer(objectInstance.GetType());
    var sb = new StringBuilder();

    using (TextWriter writer = new StringWriter(sb))
    {
        serializer.Serialize(writer, objectInstance);
    }

    return sb.ToString();
}

public static T XmlDeserializeFromString<T>(this string objectData)
{
    return (T)XmlDeserializeFromString(objectData, typeof(T));
}

public static object XmlDeserializeFromString(this string objectData, Type type)
{
    var serializer = new XmlSerializer(type);
    object result;

    using (TextReader reader = new StringReader(objectData))
    {
        result = serializer.Deserialize(reader);
    }

    return result;
}

To use it:

//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();

//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>(); 

If you have the XML stored inside a string variable you could use a StringReader:

var xml = @"<car/>";
var serializer = new XmlSerializer(typeof(Car));
using (var reader = new StringReader(xml))
{
    var car = (Car)serializer.Deserialize(reader);
}

1-liner, takes a XML string text and YourType as the expected object type. not very different from other answers, just compressed to 1 line:

var result =  (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));

static T DeserializeXml<T>(string sourceXML) where T : class
{
    var serializer = new XmlSerializer(typeof(T));
    T result = null;

    using (TextReader reader = new StringReader(sourceXML))
    {
        result = (T) serializer.Deserialize(reader);
    }

    return result;
}