How can I insert a node before an other using dom4j?
Asked Answered
F

1

6

I have a org.dom4j.Document instance that is a DefaultDocument implementation to be specific. I would like to insert a new node just before an other one. I do not really understand the dom4j api, I am confused of the differences between Element and DOMElement and stuff.

org.dom4j.dom.DOMElement.insertBefore is not working for me because the Node I have is not a DOMElement. DOMNodeHelper.insertBefore is nor good because I have org.dom4j.Node instances and not org.w3c.dom.Node instances. OMG.

Could you give me a little code snippet that does this job for me?

This is what I have now:

// puts lr's to the very end in the xml, but I'd like to put them before 'e'
for(Element lr : loopResult) {
  e.getParent().add(lr);
}
Fortyfour answered 27/9, 2011 at 15:5 Comment(3)
what is the variable e? Could you provide some more contextLouella
...and also, is there a way to sort the elements based on some attributes or the data they are carrying. For example you could use org.dom4j.DocumentHelper.sort(List nodes, String expression)Louella
The variable e mentioned in the snippet is also an Element, nothing special about it nor its parent. The e.getParent() is just a general Element, more specifically a node in my xml tree.Fortyfour
W
14

It's an "old" question, but the answer may still be relevant. One problem with the DOM4J API is that there are too many ways to do the same thing; too many convenience methods with the effect that you cannot see the forest for the trees. In your case, you should get a List of child elements and insert your element at the desired position: Something like this (untested):

// get a list of e's sibling elements, including e
List elements = e.getParent().elements();
// insert new element at e' position, i.e. before e
elements.add(elements.indexOf(e), lr);

Lists in DOM4J are live lists, i.e. a mutating list operation affects the document tree and vice versa

As a side note, DOMElement and all the other classes in org.dom4j.dom is a DOM4J implementation that also supports the w3c DOM API. This is rarely needed (I would not have put it and a bunch of the other "esoteric" packges like bean, datatype, jaxb, swing etc, in the same distribution unit). Concentrate on the core org.dom4j, org.dom4j.tree, org.dom4j.io and org.dom4j.xpathpackages.

Weaks answered 9/10, 2011 at 20:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.