title: Register namespace with libxml++ for XPath
body: <p>I wrote a C++ XPath parser with the <a href="http://libxmlplusplus.sourceforge.net/docs/manual/html/" rel="nofollow noreferrer">libxml++</a> library, which was built on the C <a href="http://www.xmlsoft.org/" rel="nofollow noreferrer">libxml2</a> library. It works great when the <code>xmlns</code> is not present in xml but it breaks when that namespace is added.</p>
  
  <p>Sample xml:</p>
  
  <pre><code>&lt;A xmlns="http://some.url/something"&gt;
    &lt;B&gt;
      &lt;C&gt;hello world&lt;/C&gt;
    &lt;B&gt;
  &lt;/a&gt;
  </code></pre>
  
  <p>Sample XPath:</p>
  
  <pre><code>string xpath = "/A/B/C" // returns nothing when xmlns is present in the XML
  </code></pre>
  
  <p>I found <a href="https://stackoverflow.com/a/5241062/1241782">this answer</a> and tried adjusting my XPath to the following, which does work but it makes the XPath kind of obnoxious to read and write.</p>
  
  <pre><code>string xpath = "/*[name()='A']/*[name()='B']/*[name()='C']"
  </code></pre>
  
  <p>Ideally I want to register the namespace so I can use normal XPaths. I've also searched through the libxml++ documentation and found a <a href="http://libxmlplusplus.sourceforge.net/docs/reference/1.0/html/classxmlpp_1_1Node.html" rel="nofollow noreferrer"><code>Node.set_namespace</code></a> but it just causes an exception when I try to use it.</p>
  
  <pre><code>root_node-&gt;set_namespace("http://some.url/something");
  // exception: The namespace (http://some.url/something) has not been declared.
  </code></pre>
  
  <p>However, the <code>root_node</code> is definitely aware of the namespace when it parses the XML document:</p>
  
  <pre><code>cout &lt;&lt; "namespace uri: " &lt;&lt; root_node-&gt;get_namespace_uri();
  // namespace uri: http://some.url/something
  </code></pre>
  
  <p>At this point I am out of ideas so help is greatly appreciated.</p>
  
  <p>EDIT Also tried:</p>
  
  <pre><code>Element *root_node = parser-&gt;get_document()-&gt;get_root_node();
  root_node-&gt;set_namespace_declaration("http://some.url/something","x");
  cout &lt;&lt; "namespace uri: " &lt;&lt; root_node-&gt;get_namespace_uri() &lt;&lt; endl;
  cout &lt;&lt; "namespace prefix: " &lt;&lt; root_node-&gt;get_namespace_prefix() &lt;&lt; endl;
  // namespace uri: http://some.url/something
  // namespace prefix: 
  </code></pre>
  
  <p>Does not complain but doesn't appear to register the namespace.</p>