title: How can I insert element into xml after/before certain element in java
body: <p>Here is my code, maybe you will notice right away what I'm missing :</p>
  
  <pre><code>DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = domFactory.newDocumentBuilder();
  Document doc = builder.parse(fileName));
  
  XPathFactory factory = XPathFactory.newInstance();
  XPath xpath = factory.newXPath();
  XPathExpression expr = xpath.compile("//CustomerId");
  
  Object result = expr.evaluate(doc, XPathConstants.NODESET);
  Nodelist nodes = (NodeList) result;
  Text a = doc.createTextNode("value");
  Element p = doc.createElement("newNode");
  p.appendChild(a);
  
  for (int i = 0; i &lt; nodes.getLength(); i++) {
      nodes.item(i).insertBefore(p, nodes.item(i));
  }
  </code></pre>
  
  <p>I'm trying to insert new node(<code>&lt;newNode&gt;value&lt;/newNode&gt;</code>) before CustomerId existing node. Here is my XML sample file :</p>
  
  <pre><code>&lt;Customer&gt;
      &lt;names&gt;
          &lt;firstName&gt;fName&lt;/firstName&gt;
          &lt;lastName&gt;lName&lt;/lastName&gt;
          &lt;middleName&gt;nName&lt;/middleName&gt;
          &lt;nickName/&gt;
      &lt;/names&gt;
      &lt;addressList&gt;
          &lt;address&gt;
              &lt;streetInfo&gt;
                  &lt;houseNumber&gt;22&lt;/houseNumber&gt;
                  &lt;baseName&gt;Street base name&lt;/baseName&gt;
                  &lt;district&gt;kewl district&lt;/district&gt;
              &lt;/streetInfo&gt;
              &lt;zipcode&gt;22231&lt;/zipcode&gt;
              &lt;state&gt;xxx&lt;/state&gt;
              &lt;country&gt;xxxz&lt;/country&gt;
              &lt;primary&gt;true&lt;/primary&gt;
          &lt;/address&gt;
      &lt;/addressList&gt;
      &lt;CustomerId/&gt;
      &lt;SSN&gt;561381&lt;/SSN&gt;
      &lt;phone&gt;
          &lt;homePhone&gt;123123123&lt;/homePhone&gt;
          &lt;officePhone/&gt;
          &lt;homePhone&gt;21319414&lt;/homePhone&gt;
      &lt;/phone&gt;
      &lt;preferred&gt;true&lt;/preferred&gt;
  &lt;/Customer&gt;
  </code></pre>
  
  <p>This is an exception getting thrown I just don't know what else to try :</p>
  
  <blockquote>
    <p>NOT_FOUND_ERR: An attempt is made to
    reference a node in a context where it
    does not exist.</p>
  </blockquote>