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);
}
jabal
  • 11,987
  • 12
  • 51
  • 99
  • what is the variable e? Could you provide some more context – peshkira Sep 27 '11 at 21:10
  • ...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) – peshkira Sep 27 '11 at 21:18
  • 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. – jabal Oct 02 '11 at 08:49

1 Answers1

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.

forty-two
  • 12,204
  • 2
  • 26
  • 36