Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception when trying to deserialize a xml file

Im trying to deserialize an XML file with XmlSerializer, however im getting this exception:

"There is an error in XML document (1, 2)" The innerexception is: "<Mymessage xmlns='http://MyMessages/'> was not expected."

Which is the very first line in the XML file. my guess is that it has something to do with the xmlns.

I tried to ask Google, and then tried to add the following line to my code

[XmlRoot("MyMessage", Namespace="'http://MyMessages/")]

But I still get the same exception.

like image 745
CruelIO Avatar asked Mar 23 '09 13:03

CruelIO


4 Answers

In the constructor of the XmlSerializer i needed to specify a default namespace, after doing that everything worked just fine

like image 163
CruelIO Avatar answered Oct 16 '22 10:10

CruelIO


Please provide the full XML file code to help understand the issue better.

Also put this as the first line in the xml file and see if this solves the issue

 <?xml version="1.0" encoding="utf-8"?>
like image 23
Binoj Antony Avatar answered Oct 16 '22 10:10

Binoj Antony


Further to CruelIO's response, I resolved the error by adding:

[XmlRoot("RenderResult", Namespace = "http://mynamespace.uri.org")]

to the class that I was trying to deserialize. e.g: the serialization code was:

RenderResult result;
using (var memoryStream = new MemoryStream(data))
{
    var xmlSerializer = new XmlSerializer(typeof(RenderResult));
    result = (RenderResult)xmlSerializer.Deserialize(memoryStream);
}

and my class looked like this:

[XmlRoot("RenderResult", Namespace = "http://mynamespace.uri.org")]
public class RenderResult
{
}
like image 2
timdougall Avatar answered Oct 16 '22 11:10

timdougall


It sounds like you have a borked xml file. Easy ways to find out:

  • try loading it into an xml viewer
  • or just make sure it has a .xml extension and load in VS or IE
  • or run xsd.exe over it

If they complain, then the xml is certainly corrupt. If they work fine, and display your data, then you probably have the serialization attributes wrong. Try using xsd.exe with the "/classes" switch to see what it would do with it...

like image 1
Marc Gravell Avatar answered Oct 16 '22 10:10

Marc Gravell