2

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"> 

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

8
  • As an aside, normally xmlReader and xmlWriter would be used for instances of XmlReader and XmlWriter, not StringReader and StringWriter. Commented Aug 18, 2010 at 19:59
  • To solve this, I think we'll need to see the declaration of MyCustomClass, as well as the rest of the XML. Commented Aug 18, 2010 at 19:59
  • It is telling me I can't create an instance of the abstract class XmlWriter Commented Aug 18, 2010 at 20:01
  • My equivalent code works good. Can you serialize empty class? Then add some properties to it. Commented Aug 18, 2010 at 20:07
  • The MyCustomClass code is fairly long... it contains no attributes other then [Serializable] and its only property is a CustomObservableCollection (inherited from base ObservableCollection) of CustomObjects. Commented Aug 18, 2010 at 20:07

3 Answers 3

1

BTW, you need using blocks around your code:

using (StringReader reader = new StringReader(xml)) { obj = (T)xmlSerializer.Deserialize(reader); } 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I will keep that in mind when doing any other debugging, Thanks
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.