Replace a node with a set of nodes
Sunday, July 13th, 2008In the last days in a my program, I should substitute a single node with a set of Node. The DOM interface (in this program I’m using the Xerces library) doesn’t provides an useful method to replace a single Node to a set of Nodes.
For apply this piece of code you should have:
- parent node: The parent of the node that you want substitute;
- target node: The node that you want substitute;
- newNodes nodes: A set of nodes that you want add to the place of target node;
The code is the follow:
1: Node previous = null;
2: for(int i = newNodes.size() -1 ; i >= 0 ; i--) {
3: Node current = newNodes.get(i);
4:
5: if(i == newNodes.size() -1) {
6: parent.replaceChild(current, target);
7: } else {
8: parent.insertBefore(current, previous);
9: }
10: previous = current;
11: }