我有一些xml文件,我试图在给定的代码中反序列化如下.
using (StreamReader srFileContent = new StreamReader(filePath)) { XmlSerializer serializer = new XmlSerializer(typeof(messageType)); messageType objMessage = (messageType)serializer.Deserialize(srFileContent); }
这里文件位于filePath不包含以下行
<?xml version="1.0"?> <message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
这就是我收到错误的原因.在反序列化给定文件的流之前,您可以帮助我如何添加此行运行时.
错误如下:
System.InvalidOperationException: There is an error in XML document
(2,2). —> System.InvalidOperationException: was
not expected. at
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReadermessageType.Read161_message()
— End of inner exception stack trace — at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader
xmlReader,String encodingStyle,XmlDeserializationEvents events) at
System.Xml.Serialization.XmlSerializer.Deserialize(TextReader
textReader) at CCR2BB.frmMain.BWConvertProcess_DoWork()
解决方法
您将不得不查看基本异常以找出问题所在.捕获的异常可能包含4个或更多内部异常.
例如:
try { ... } catch (Exception ex) { Console.WriteLine(ex.GetBaseException()); }