title: Deserializing a single element in a large XML document: xmlSerializer.Deserialize(xmlReader.ReadSubtree()) fails due to namespace issues
body: <p>I am attempting to process a large XML document (using a <code>XmlReader</code>) in a single pass, and deserialize only certain elements in it using an <code>XmlSerializer</code>.</p>
  
  <p>Below is some code and a tiny mock XML document showing how I have attempted to do this.</p>
  
  <blockquote>
    <p><sup><strong>Rationale for using <code>XmlReader</code>:</strong> <strong>1.</strong> I am dealing with very large XML documents (10&ndash;250 MB), which for this reason I do not want to load into memory. So <code>XmlDocument</code> is out of the question. <strong>2.</strong> I want to extract only certain elements. Typically I will be able to ignore most other content. <code>XmlReader</code> appears to give me an efficient means of skipping irrelevant content. <strong>3.</strong> I do not know in advance whether any and all elements that I can deal with will be present; therefore I am not using a bunch of <code>Xpath</code>/<code>XQuery</code> or LINQ to XML-based queries, because I want to make only a single pass over the XML files (due to their size).</sup></p>
  </blockquote>
  
  <pre><code>public class ElementOfInterest { }
  …
  
  var xml = @"&lt;?xml version='1.0' encoding='utf-8' ?&gt;
              &lt;Root xmlns:ex='urn:stakx:example'
                    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'&gt;
                &lt;ElementOfInterest xsi:type='ex:ElementOfInterest' /&gt;
              &lt;/Root&gt;";
  
  var reader = System.Xml.XmlReader.Create(new System.IO.StringReader(xml));
  reader.ReadToFollowing("ElementOfInterest");
  
  var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ElementOfInterest));
  serializer.Deserialize(reader.ReadSubtree());
  </code></pre>
  
  <p>The last line of code throws the following inner exception:</p>
  
  <blockquote>
    <p><em><code>InvalidOperationException</code>: "Namespace prefix <code>ex</code> is not defined."</em></p>
  </blockquote>
  
  <p>Obviously, the <code>XmlSerializer</code> doesn't recognise the <code>ex</code> namespace prefix inside the <code>xsi:type</code> attribute's value.</p>
  
  <p>This is just one error I am having, but frankly, the larger problem is that I have no idea how to go about the whole namespace issue. I am simply looking for a convenient way to de-serialize just a single node out of the XML document, but that seems to entail having to manually register/manage namespaces, and to somehow forward them from the <code>XmlReader</code> to the <code>XmlSerializer</code>.</p>
  
  <p>Can someone demonstrate how to deserialize a single node from a XML document read with an <code>XmlReader</code>, either by pointing out the error in my code, or by showing an alternative approach?</p>