views:

57

answers:

3

I am trying to serialize an object into the database using xml serialization, however when deserializing it I am getting an error.

The error is There is an error in XML document (2, 2) with an inner exception of "<MyCustomClass xmlns=''> was not expected."

The code I am using to serialize is:

public static string SerializeToXml<T>(T obj)
{
    if (obj == null)
        return string.Empty;

    StringWriter xmlWriter = new StringWriter();
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    xmlSerializer.Serialize(xmlWriter, obj);
    return xmlWriter.ToString();
}

public static T DeserializeFromXml<T>(string xml)
{
    if (xml == string.Empty)
        return default(T);

    T obj;
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    StringReader xmlReader = new StringReader(xml);
    obj = (T)xmlSerializer.Deserialize(xmlReader);
    return obj;
}

The SerializedXml begins with:

<?xml version="1.0" encoding="utf-16"?>
<MyCustomClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;

This is my first time using serialization and I'm wondering what I'm doing something wrong with my code.

+1  A: 

BTW, you need using blocks around your code:

using (StringReader reader = new StringReader(xml))
{
    obj = (T)xmlSerializer.Deserialize(reader);
}
John Saunders
Thanks, I will add that
Rachel
+1  A: 

Unfortunately, XmlSerialization exceptions is a piece of crap.

You normally have to drill down into countless levels of inner exceptions to get to the real error.

leppie
I will keep that in mind when doing any other debugging, Thanks
Rachel
+1  A: 

I'm sorry, I just realized my problem was stupidity =/

I was serializing the class but trying to deserialize the ObservableCollection only. Once I changed that to serializing/deserialing the correct object it works great, although I thank you for the tip about using blocks

Rachel