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.
xmlReaderandxmlWriterwould be used for instances ofXmlReaderandXmlWriter, notStringReaderandStringWriter.MyCustomClass, as well as the rest of the XML.[Serializable]and its only property is a CustomObservableCollection (inherited from base ObservableCollection) of CustomObjects.