title: "Namespace 'x' is not defined" despite calling GetNamespacesInScope first
body: <p>I'm trying to parse a valid XML document in c# .NET using <code>xPathNavigator</code>. The start of the XML document looks like this:</p>
  
  <pre><code>&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
      &lt;soapenv:Body&gt;
          &lt;ns1:myResponse xmlns:ns1="ExampleNS" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"&gt;
              &lt;myReturn href="#2" /&gt;
  </code></pre>
  
  <p>As you can see, there's some namespaces defined on the root element, but then <code>ns1</code> is defined later on. When I try and evaluate an xPath query <code>/soapenv:Envelope/soapenv:Body/ns1:myResponse/myReturn</code> I get an <code>XPathException</code>: </p>
  
  <pre><code>Namespace prefix 'ns1' is not defined.
  </code></pre>
  
  <p>What I'm doing is getting the XML document as a string, loading it into an <code>XmlDocument</code> object. Then I'm creating a navigator, moving to the root element and calling <code>GetNamespacesInScope(XmlNamespaceScope.All)</code>. I loop through this collection, which contains the namespaces for <code>xml</code>, <code>soapenv</code>, <code>xsd</code> and <code>xsi</code> as defined on the root, adding them to the namespacemanager. Then I create an <code>xPathNavigator</code> and call <code>Evaluate</code>, and get the exception.</p>
  
  <p>Code is this:</p>
  
  <pre><code>string response = GetXMLString();
  var xmlDocument = new XmlDocument();
  xmlDocument.LoadXml(response);
  
  var xmlDocumentNavigator = xmlDocument.CreateNavigator();
  xmlDocumentNavigator.MoveToFollowing(XPathNodeType.Element);
  var xnm = new XmlNamespaceManager(xmlDocument.NameTable);
  var namespacesInScope = xmlDocumentNavigator.GetNamespacesInScope(XmlNamespaceScope.All);
  if (namespacesInScope != null)
  {
      foreach (var prefix in namespacesInScope.Keys)
      {
          xnm.AddNamespace(prefix, namespacesInScope[prefix]);
      }
  }
  
  var xPathDocument = new XPathDocument(new StringReader(response));
  var xPathNavigator = xPathDocument.CreateNavigator();
  
  xPathNavigator.Evaluate("/soapenv:Envelope/soapenv:Body/ns1:myResponse/myReturn", xnm);
  </code></pre>
  
  <p>Why doesn't the <code>GetNamespacesInScope</code> method pick up on <code>ns1</code>?</p>