tags:

views:

37

answers:

1

I am trying to remove and add similar nodes in a document tree

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); 

what would be the ideal way to add element to doc ? the remove loop works fine

A: 

Something like the following will add an element:

Element newElement = doc.createElement("foo");
parentElm.appendChild(newElement);

This will create a new child element <foo/> and will only work if the parentElm is from the same document as doc. There's also a namespace-aware version which is likely to be more useful in real situations.

If you need to add a new element at an exact position amongst several existing siblings (say, insert an element in between two existing children) you can get a reference to the latter sibling and use the insertBefore method.

Andrzej Doyle