7

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.

2
  • could you share the relevant part of the xml file please? Commented Mar 23, 2009 at 14:11
  • This is an old question but it's important to know that same error can be generated due to a class missing a Serializable attribute. Commented Jan 30, 2012 at 18:03

4 Answers 4

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

Can you give a code example of how you solved this? I think I am having the same issue, but specifying the default namespace does not make a difference.
3

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"?> 

1 Comment

I would strongly recommend to use "utf-8" instead of iso-8859-1 for all interopertable web service work!
2

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 { } 

Comments

1

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...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.