title: Add Element to Document and find with XPath
body: <p>I have code that searches XML Documents (org.w3c.dom) using namespace-aware XPath. I am having issues with adding elements to the document and then being able to find them via the XPath.</p>
  
  <p>If I add the elements and search using the XPath I do not get any result. However, if I convert the Document to a String and reparse to a Document, the XPath finds the element. </p>
  
  <p>I create the XPath as follows:</p>
  
  <pre><code>String myXPathQuery = "/ns1:element1/ns2:element2/ns3:element3";
  XPathFactory fact = XPathFactory.newInstance();
  XPath xpath = fact.newXPath();
  xpath.setNamespaceContext(myNSContext);
  XPathExpression myXPathExpression = xpath.compile(myXPathQuery);
  </code></pre>
  
  <p>I am adding the element as follows:</p>
  
  <pre><code>Document doc = ...;
  Element elementToWhichToAdd = ...; // this is "ns2:element2"
  
  Element newElement = doc.createElement("ns3:element3");
  elementToWhichToAdd.appendChild(newElement);
  </code></pre>
  
  <p>If I run the above XPath against this Document it doesn't find anything. But if I reparse the Document the XPath works.</p>
  
  <p>What am I missing?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>As part of the process by which I update the document I add the Namespace if it does not exist (it usually does not).</p>
  
  <pre><code>Element rootElement = doc.getDocumentElement();
  NamedNodeMap map = rootElement.getAttributes();
  if (map.getNamedItem("xmlns:ns3") == null)
       rootElement.setAttributeNS("http://www.w3.org/2000/xmlns", "xmlns:ns3",
              "urn:exo:/path/to/xsd/in/jar");
  </code></pre>