From a console app, I make a call to a Web API. The API returns an IEnumerable<Foo>
as XML. The XML response looks like this:
<ArrayOfFoo xmlns:i="..." xmlns="....">
<Foo>
<Member1>First Foo</Member1>
<Member2>Yes</Member2>
...
</Foo>
<Foo>
...
</Foo>
</ArrayOfFoo>
When I try to deserialize it in the console app into a List<Foo>
, it doesn't work. The exception reported is:
<ArrayOfFoo xmlns='http://schemas.datacontract.org/2004/07/TheFooThing.Model'>
was not expected.
Here's the code I use to deserialize the response:
string xml;
using(var reader = new StreamReader(responseStream))
{
xml = reader.ReadToEnd();
}
// deserialize into shape IEnumerable<T>
var listOfFoos = new List<Foo>();
var resultType = listOfFoos.GetType();
var serializer = new XmlSerializer(resultType);
var doc = XDocument.Parse(xml);
using(var reader = doc.CreateReader())
{
listOfFoos = serializer.Deserialize(reader) as List<Foo>;
}
return listOfFoos;
Note: I use the old HttpWebRequest
to make the HTTP request and get a response from the API. No particular reason for choosing this and not choosing the HTTPClient
.