今天遇到了一个XML 反序列化的问题,我使用的C#编程,序列化和反序列化的操作很简单,代码如下:
反序列 XML 转 Object
//Xml To Object
public static T Deserializer(string XML)
{
try
{
if (string.IsNullOrEmpty(XML))
{
return default(T);
}
var stream = new System.IO.StringReader(XML);
System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(T));
//序列化对象
//xmlfile.Close();
T t = (T)xml.Deserialize(stream);
return t;
}
catch (InvalidOperationException)
{
throw;
}
catch (System.IO.FileNotFoundException)
{ throw; }
finally
{
}
}
//Object To XML
public static string Serializer(object obj)
{
FileStream xmlfile = new FileStream();
string XMLString= null;
//创建序列化对象
XmlSerializer xml = new XmlSerializer(typeof(T));
try
{ //序列化对象
xml.Serialize(xmlfile, obj);
StreamReader reader = new StreamReader(xmlfile);
XMLString = reader.ReadToEnd();
xmlfile.Close();
}
catch (InvalidOperationException)
{
throw;
}
return XMLString;
}
//Xml To Object 从本地文件读取
public static bool Serializer(object obj, string path)
{
FileStream xmlfile = new FileStream(path, FileMode.OpenOrCreate);
//创建序列化对象
XmlSerializer xml = new XmlSerializer(typeof(T));
try
{ //序列化对象
xml.Serialize(xmlfile, obj);
xmlfile.Close();
}
catch (InvalidOperationException)
{
throw;
}
return true;
}
//Object To XML 直接写到本地文件
public static bool Serializer(object obj, string path)
{
FileStream xmlfile = new FileStream(path, FileMode.OpenOrCreate);
//创建序列化对象
XmlSerializer xml = new XmlSerializer(typeof(T));
try
{ //序列化对象
xml.Serialize(xmlfile, obj);
xmlfile.Close();
}
catch (InvalidOperationException)
{
throw;
}
return true;
}
然而转换成Object时报了 错,异常如下
There is an error in XML document (1, 2). ---> System.InvalidOperationException: was not expected.
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderData.Read5_data()
其实是和返回的Object有关系,在Object头加上一个特性,如下:
[XmlRoot("xml"), XmlType("xml")]
public class xmlstring {...}
注意:这两个属性的值对应的是XML文本的根节点的标签,如我上面的这个类只能转化如下标准的XML
<xml>
<id></id>
................................
</xml>详细参照:https://stackoverflow.com/questions/4884383/error-deserializing-xml-to-object-xmlns-was-not-expected
本文讲述了在使用C#进行XML反序列化时遇到的问题,详细描述了一个异常情况:There is an error in XML document (1, 2)。原因是预期的对象类型与XML数据不匹配。解决方案是在目标对象类的头部添加适当的特性来匹配XML结构。"
114409443,10535890,Python Pandas 数据处理:深入理解 dtypes,"['pandas', '数据处理', '数据类型', '转换函数', '数据帧']
1万+

被折叠的 条评论
为什么被折叠?



