开发者

XmlSerialization throwing error when deserializing?

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=''> w开发者_开发技巧as 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">

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


BTW, you need using blocks around your code:

using (StringReader reader = new StringReader(xml))
{
    obj = (T)xmlSerializer.Deserialize(reader);
}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜