如何使用dom4j在其他节点之前插入节点? [英] How can I insert a node before an other using dom4j?

查看:454
本文介绍了如何使用dom4j在其他节点之前插入节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个org.dom4j.Document实例,该实例是要特定的DefaultDocument实现.我想在另一个节点之前插入一个新节点.我不太了解dom4j api,我对ElementDOMElement以及其他内容之间的区别感到困惑.

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对我不起作用,因为我拥有的节点不是DOMElement. DOMNodeHelper.insertBefore也不是很好,因为我有org.dom4j.Node实例而不是org.w3c.dom.Node实例.天哪.

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?

这就是我现在拥有的:

// 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);
}

推荐答案

这是一个旧"问题,但答案可能仍然很重要. DOM4J API的一个问题是做同一件事的方法太多了.太多的便利方法,结果使您看不见树木的森林.对于您的情况,应该获得子元素列表,然后将元素插入所需的位置:像这样(未经测试):

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);

DOM4J中的列表是活动列表,即,变异列表操作会影响文档树,反之亦然

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

请注意,DOMElement和org.dom4j.dom中的所有其他类是DOM4J实现,它也支持w3c DOM API.这很少需要(我不会把它和一堆其他深奥的"包装,如bean,数据类型,jaxb,swing等放在同一分发单元中).专注于核心org.dom4jorg.dom4j.treeorg.dom4j.ioorg.dom4j.xpath软件包.

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.

这篇关于如何使用dom4j在其他节点之前插入节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆