Error in XML document (2.2)

I have several xml files and am trying to deserialize as shown below in this code.

using (StreamReader srFileContent = new StreamReader(filePath)) { XmlSerializer serializer = new XmlSerializer(typeof(messageType)); messageType objMessage = (messageType)serializer.Deserialize(srFileContent); } 

Here, the locate at filePath file does not contain the following lines

 <?xml version="1.0"?> <message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

and that’s why I get the error. Can it help me how to add this line to runtime before deserializing the stream of the given file.

The error is given below:

System.InvalidOperationException: There is an error (2, 2) in the XML document. ---> System.InvalidOperationException: was unexpected. at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReadermessageType. Read161_message () --- End of internal check for exception stack --- in System.Xml.Serialization.XmlSerializer.Deserialize (XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events) on System.Xml.Serialization.XmlSerializer.Deserialize (TextReader textReader) in CCR2BB .frmMain.BWConvertProcess_DoWork ()

+6
source share
3 answers

You will need to look at the basic exception to find out the problem. An excluded exception probably contains 4 or more internal exceptions.

EG:

 try { ... } catch (Exception ex) { Console.WriteLine(ex.GetBaseException()); } 
+12
source

The solution in another question was:

 XmlRootAttribute xRoot = new XmlRootAttribute(); xRoot.ElementName = "message"; // xRoot.Namespace = "http://www.cpandl.com"; xRoot.IsNullable = true; XmlSerializer xs = new XmlSerializer(typeof(messageType),xRoot); 

Perhaps this is an approach to your problem. Since MSDN is not available for my network, I cannot provide more documentation for XmlRootAttribute.

+3
source

Where did you get the messageType class?

If you created xsd for xml using xsd.exe and then using xsd you created this class.

Then your project will have two files that contain this class.

  • One of the designer.cs files that contains this class, which is derived from the DataSet class
  • One file is just a .cs file that has a partial class.
  • When you use this class when deserializing, it will refer to the class from designer.cs, which is obtained from the DataSet .
  • But if you remove designer.cs from your project, your code will reference the partial class from the .cs file.

By deleting this designer.cs file that had a class derived from the DataSet , I was able to resolve this error.

0
source

Source: https://habr.com/ru/post/916558/


All Articles