Mohammad
Mohammad

Reputation: 2764

deserialize xml string to object

i wrote this method in order to convert a xml string into the object:

private object Deserializer(Type type)
{
    object instance = null;
    try
    {
        XmlSerializer xmlSerializer = new XmlSerializer(type);
        using (StringReader stringreader = new StringReader(somestring))
        {
            instance = (type)xmlSerializer.Deserialize(stringreader);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return instance;
} 

but here:

instance = (type)xmlSerializer.Deserialize(stringreader);

this error shows up: The type or namespace name 'type' could not be found (are you missing a using directive or an assembly reference?) how can i fix it?

Upvotes: 5

Views: 14989

Answers (2)

Aht
Aht

Reputation: 593

But what is a Type is class that u made or what ?

Maybe u want do to :

private object Deserializer<T>(T type)

Edit Try this :

private static T LoadData<T>() where T : new ()
    {
        using (var reader = new StreamReader(@_path))
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
            return (T) xmlSerializer.Deserialize(reader);
        }

    }

Upvotes: 3

Guy Levin
Guy Levin

Reputation: 1258

You canno't cast to "type" you need to specify the exact type like this (for string):

(string)xmlSerializer.Deserialize(stringreader);

Maybe consider using generic function like this:

private T Deserializer<T>()
{
    T instance = null;
    try
    {
        var xmlSerializer = new XmlSerializer(typeof(T));
        using (var stringreader = new StringReader(somestring))
        {
            instance = (T)xmlSerializer.Deserialize(stringreader);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return instance;
} 

and than call the function like this:

var instance = xmlSerializer.Deserialize<SomeType>();

if you want to specify the type only in runtime you can use:

instance = Convert.ChangeType(xmlSerializer.Deserialize(stringreader), type);

Upvotes: 12

Related Questions