今天遇到了一個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