InvalidOperationException: <Error xmlns=''> was not expected.

Julio Bello 221 Reputation points
2023-09-19T17:36:24.61+00:00

Hi, Everybody!

I need to deserialize the following XML...

<?xml version="1.0" encoding="utf-8"?>
<Error>
	<Message> There is an error in....</Message>
</Error>

I defined the following class...

[XmlRoot(ElementName="Error")]
public class Error { 

	[XmlElement(ElementName="Message")] 
	public string Message { get; set; } 
}

When I attempt to deserialize...

        private TResponse XmlStringToObject<TResponse>(string xmlString)
        {
            using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
            {
                var xmlSerializer = new XmlSerializer(typeof(TResponse));

                return (TResponse)xmlSerializer.Deserialize(memoryStream);
            }
        }

I get the following error message...

System.InvalidOperationException HResult=0x80131509 Message=There is an error in XML document (1, 40). Source=<Cannot evaluate the exception source> Inner Exception 1: InvalidOperationException: <Error xmlns=''> was not expected.

What am I doingwrong?

Developer technologies | .NET | .NET Runtime
Developer technologies | .NET | Other
Developer technologies | C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2023-09-19T18:28:30.04+00:00

    I think that TResponse was not Error in your call of XmlStringToObject<TResponse>.

    Or maybe the real details were different.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.