简体   繁体   English

Dom4j从一个xml分离/复制节点并添加到另一个

[英]Dom4j Detach/Copy node from one xml and add to another

I am actually traversing src xml and converting it into another destination xml. 我实际上遍历src xml并将其转换为另一个destination xml。 But part of src xml will be just copied and added to the destination . 但是src xml的一部分将被复制并添加到destination But when I am trying to do that I am getting following Exception: 但是当我尝试这样做时,我得到以下异常:

could not be added to the element "<DestinationParent>" because: The Node already has an existing parent of "<SourceParent"

I am traversing src XML and calling this function 我正在遍历src XML并调用此函数
Code

private static Element treeWalk (Element rootElement, Element parentElement)
{
    Element moduleRootElement = doc.addElement("Request");
    if(rootElement.getName()=="someName")
    {
        moduleRootElement.add(childElement.getName());
    } else {
        moduleRootElement.add(rootElement); //If root's parent is not null I get a exception here.
        //moduleRootElement= rootElement.createCopy(); //Didn't work
    }
}

You need to call detach() on the node you want to move. 您需要在要移动的节点上调用detach() From the dom4j JavaDocs dom4j JavaDocs

Node node = ...; 
Element someOtherElement = ...; 
someOtherElement.add( node.detach() );

Since Element implements Node if you need to convert back to Element you can do it just by casting (provided you know that the thing you detached was an Element ). 由于Element如果需要将其转换回Element ,则可以实现Node ,因此可以通过强制转换来实现(前提是您知道分离的对象是Element )。 Another option for you might be to copy the Element . 您的另一个选择可能是复制Element Using your code as a starting point: 以您的代码为起点:

Element moduleRootElement = doc.addElement("Request");
if (rootElement.getName().equals("someName") {
    moduleRootElement.add(childElement.getName());
} else {
    moduleRootElement.add(rootElement.createCopy());
}

It looks like you actually tried this, but didn't quite get all the way there. 看起来您实际上已经尝试过了,但是并没有完全解决问题。 Remember, in java using = reassigns the variable to the new object. 请记住,在Java中,使用=将变量重新分配给新对象。 All the existing references to it are broken. 现有的所有引用均已损坏。

As a side note, you probably also need to check your root element's name with 附带说明,您可能还需要使用以下命令检查根元素的名称

if(rootElement.getName().equals("someName"))

instead of using == 而不是使用==

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM