title: DataContractSerializer and deserializing web service response types
body: <p>I am using calling web services and using WCF generated service-reference on the client.  I have saved XML responses that are received from test service to disk (without SOAP envelope and body tags) I would like to load them from disk and create objects from them. Lets' take the following method from my web service:</p>
  
  <pre><code>SomeMethodResponse SomeMethod(SomeMethodRequest req)
  </code></pre>
  
  <p>I manually (through SOAP UI) save the response to disk to file, Sample response:</p>
  
  <pre><code>&lt;SomeMethodResponse xmlns="http://myNamespace"&gt;
      &lt;SomeMember1&gt;value&lt;/SomeMember1&gt;
  &lt;/SomeMethodResponse&gt;
  </code></pre>
  
  <p>Then I try to deserialize the object from file using:</p>
  
  <pre><code>DataContractSerializer dcs = 
    new DataContractSerializer(typeof(SomeMethodResponse))
  </code></pre>
  
  <p>This fails – the serializer complains with the error, that it is expecting element in namespace '<a href="http://schemas.datacontract.org/2004/07" rel="nofollow noreferrer">http://schemas.datacontract.org/2004/07</a>', but found element in '<a href="http://myNamespace" rel="nofollow noreferrer">http://myNamespace</a>'.</p>
  
  <p><strong>Question:</strong> Why does  the <code>DataContractSerializer</code> not use the namespace, that is declared on SomeMethodResponseType with <code>XmlTypeAttribute(Namespace="http://myNamespace")</code>?</p>
  
  <p>I can work around this by explicitly providing the namespace and the root element to <code>DataContractSerializer</code> constructor. But then it fails with message similar to:</p>
  
  <p><em>Error in line X position Y (last line of the XMLdocument). 'EndElement' 'SomeMethodResponse<br>
  from namespace 'httpmyNapespace’ is not expected.
  Expecting element 'someNameField'.</em></p>
  
  <p><code>SomeName</code> is an element in the XSD that web service is using. It is also a property on the <code>SomeMethodResponse</code> type, backed by the private field called <code>someNameField</code>. It looks like <code>DataContractSerializer</code> is trying to deserialize the fields in addition to properties.</p>
  
  <p>How can I deserailize XML that I have saved from disk and get back the object of same type that SomeMethod is returning?</p>
  
  <p>Thanks,
    Matra</p>