Rickard Öberg wrote: > > Hi! > > I'm using Xerces and am having trouble with a particular problem. > > Problem: > I have a Document object where I need to replace the document element > with a new one. Essentially, I am building a XML document editor, where > I first read in the document, edit the nodes as Java objects and then > export the object hierarchy to XML nodes again. > > Solution 1: > Use doc.replaceChild(newRoot,doc.getDocumentElement()); > But this didn't work because the implementation tried to insert the new > node before the old one was removed -> structural error. Isn't this a > bug?? > > Solution 2: > Remove all old children, and insert the new ones: > ------- > Element oldNode = doc.getDocumentElement(); > NodeList list = oldNode.getChildNodes(); > for (int i = 0; i < list.getLength(); i++) > oldNode.removeChild(list.item(i)); > > list = newRoot.getChildNodes(); > for (int i = 0; i < list.getLength(); i++) > oldNode.appendChild(list.item(i)); > -------- > But this only removes the text nodes of the root document for some > reason. I thought that getChildNodes retrieved all nodes?? Anyway, > calling oldNode.hasChildNodes() after the removal returns true.. bug? > > Workaround: > Does anyone know a working solution to this problem? It's a showstopper > for me right now...
Get a new Document implementation instance (I don't have the JavaDoc here, sorry), then create from there a new Element node. Do your editing modifying all the child elements of this, and then, after the modification is complete, append it to the new Document you created... It works... Pier