【发布时间】:2010-08-18 19:54:26
【问题描述】:
我正在尝试使用 xml 序列化将对象序列化到数据库中,但是在反序列化它时出现错误。
错误是XML文档中存在错误(2, 2),内部异常为"<MyCustomClass xmlns=''> was not expected."
我用来序列化的代码是:
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;
}
SerializedXml 开头为:
<?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">
这是我第一次使用序列化,我想知道我的代码做错了什么。
【问题讨论】:
-
顺便说一句,通常
xmlReader和xmlWriter将用于XmlReader和XmlWriter的实例,而不是StringReader和StringWriter。 -
要解决这个问题,我想我们需要查看
MyCustomClass的声明,以及XML 的其余部分。 -
它告诉我我无法创建抽象类 XmlWriter 的实例
-
我的等效代码运行良好。你可以序列化空类吗?然后给它添加一些属性。
-
MyCustomClass 代码相当长...它不包含除
[Serializable]之外的任何属性,其唯一属性是CustomObjects 的CustomObservableCollection(继承自基本ObservableCollection)。
标签: c# xml-serialization serialization