title: XML namespaces and XPath
body: <p>I have an application that has to load XML document and output nodes depending on XPath.</p>
  
  <p>Suppose I start with a document like this:</p>
  
  <pre><code>&lt;aaa&gt;
    ...[many nodes here]...
    &lt;bbb&gt;text&lt;/bbb&gt;
    ...[many nodes here]...
    &lt;bbb&gt;text&lt;/bbb&gt;
    ...[many nodes here]...
  &lt;/aaa&gt;
  </code></pre>
  
  <p>With XPath <code>//bbb</code></p>
  
  <p>So far everything is nice.</p>
  
  <p>And selection <code>doc.SelectNodes("//bbb");</code> returns the list of required nodes.</p>
  
  <p>Then someone uploads a document with one node like <code>&lt;myfancynamespace:foo/&gt;</code> and extra namespace in the root tag, and everything breaks.</p>
  
  <p>Why? <code>//bbb</code> does not give a damn about <code>myfancynamespace</code>, theoretically it should even be good with <code>//myfancynamespace:foo</code>, as there is no ambiguity, but the expression returns 0 results and that's it.</p>
  
  <p>Is there a workaround for this behavior?</p>
  
  <p>I do have a namespace manager for the document, and I am passing it to the Xpath query. But the namespaces and the prefixes are unknown to me, so I can't add them before the query.</p>
  
  <p>Do I have to pre-parse the document to fill the namespace manager before I do any selections? Why on earth such behavior, it just doesn't make sense.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I'm using:
  <code>XmlDocument</code> and <code>XmlNamespaceManager</code></p>
  
  <p><strong>EDIT2:</strong></p>
  
  <pre><code>XmlDocument doc = new XmlDocument();
  doc.XmlResolver = null;
  XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
  //I wish I could:
  //nsmgr.AddNamespace("magic", "http://magicnamespaceuri/
  //...
  doc.LoadXML(usersuppliedxml);
  XmlNodeList nodes = doc.SelectNodes(usersuppliedxpath, nsmgr);//usersuppliedxpath -&gt; "//bbb"
  
  //nodes.Count should be &gt; 0, but with namespaced document they are 0
  </code></pre>
  
  <p><strong>EDIT3:</strong>
  Found an article which describes the actual scenario of the issue with one workaround, but not very pretty workaround: <a href="http://codeclimber.net.nz/archive/2008/01/09/How-to-query-a-XPath-doc-that-has-a-default.aspx" rel="noreferrer">http://codeclimber.net.nz/archive/2008/01/09/How-to-query-a-XPath-doc-that-has-a-default.aspx</a></p>
  
  <p>Almost seems that stripping the xmlns is the way to go...</p>