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?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,861 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,936 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,161 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 117.4K 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.