title: add a node in document in java
body: <p>I am trying to remove and add similar nodes in a document tree</p>
  
  <pre><code>Element firstItem = (Element) links.item(0);
  Element element = (Element)firstItem.cloneNode(true);
  int length = links.getLength();
  while (0 != length) {
      System.out.println("removing element #" + l + " Length: " + length);
      Element link1 = (Element) links.item(0);
      Element parentElm = (Element) link1.getParentNode();
      parentElm.removeChild(link1);
      length--;
  }
  
  // this gives a null pointer exception           
  doc.getParentNode().insertBefore(element, null); 
  </code></pre>
  
  <p>what would be the ideal way to add element to doc ? the remove loop works fine</p>