Pittfall Pittfall -3 years ago 128
C# Question

How do I deserialize a soap response that is just one element?

So after I get my response I do (Where

in this case is

var theResult = response.Content.ReadAsStringAsync().Result;
using (var stringreader = new StringReader(theResult))
var serializer = new XmlSerializer(typeof(T));
var responseObj = (T)serializer.Deserialize(stringreader);


<string xmlns="http://tempuri.org/">Hello World</string>

When I do the
I get an exception.
<string xmlns='http://tempuri.org/'> was not expected.
as the inner exception and
There is an error in XML document (2, 2).
as the message.

I am trying deserialize
Hello World
to a string or deserialize to an object when I have multiple elements with a more than just a root element. When there is a root element with more members, I think I have that figured out.

Answer Source

In order to fix the issue, you need to create the serializer with the default namespace:

var serializer = new XmlSerializer(typeof(T), "http://tempuri.org/");
var responseObj = (T)serializer.Deserialize(stringreader);

You can read alittle more on this in the link below:

for example if your using a custome class you can define a specific classname for the XmlSerialier

[XmlRoot( Namespace="urn:my-namespace" )]
public class MyClass
    public string MyField;

You can read more on this in the link above.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download