0

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.

Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336
  • Remove the namespaces from the xml string before passing it to `XDocument.Parse`. – kennyzx Jan 17 '15 at 04:54
  • Oh, there are already [some great answers](http://stackoverflow.com/questions/1556874/user-xmlns-was-not-expected-deserializing-twitter-xml) to your question. – kennyzx Jan 17 '15 at 04:59

1 Answers1

0

Looks like that was generated with DataContractSerializer not XmlSerializer. The former uses http://schemas.datacontract.org/2004/07/Clr.Namespace for its default namespace, whereas XmlSerializer does not specify a default namespace by default. You could switch to DataContractSerializer, or pass the correct default namespace to the XmlSerializer constructor:

string xml;
using(var reader = new StreamReader(responseStream))
{
    xml = reader.ReadToEnd();
}

var serializer = new XmlSerializer(typeof(List<Foo>), "http://schemas.datacontract.org/2004/07/TheFooThing.Model");
using (var reader = new StringReader(xml))
{
    var listOfFoos = serializer.Deserialize(reader) as List<Foo>;
    return listOfFoos;
}
dbc
  • 104,963
  • 20
  • 228
  • 340