PDA

View Full Version : how to insert imported node without HIERARCHY_REQUEST_ERR


wac
12-08-2004, 05:52 PM
I'm importing an element node and trying to insert it before another element node and I keep getting hierarchy request error.
Basically I'm trying to reparent a collection of nodes, but eventually I want to be able to do include.
I try to import the nodes to be included and insert them before the <import> tag but I keep getting hierarchy request error. Has anyone done something like this? I can't use XSL because the corporate solution doesn't include XSL

wac
12-08-2004, 06:04 PM
just incase anyone cared, here's the code I use
// Document doc assigned elsewhere
/*
* merge the children of this element with the
* children of the parent element and remove this element.
* This should be equivalent to commenting out the tag
* but including its children.
*/
Node importNode = null ;
NodeList children = node.getChildNodes() ;

for (int i=0; i<children.getLength(); i++)
try
{
importNode = doc.importNode(children.item(i), true) ;
doc.insertBefore(node, importNode) ;
}
catch (Exception e)
{
}

Alex Vincent
12-09-2004, 03:45 AM
How about:

importNode = doc.importNode(children.item(i), true).cloneNode(true);

What this does is create a "deep clone" of the imported node. The cloned node doesn't then have any parent node or owner document issues.

What platform are you writing this code to run on?

UPDATE: Oh, I see what you did wrong. The node you're inserting comes before the node that's already there according to the DOM.

foo.insertBefore(newChild, oldChild);

Just switch your arguments around.

wac
12-09-2004, 04:29 PM
d'oh :eek:
Thanx :thumbsup: