0

Here's my code:

private NodeList union(NodeList left, NodeList right){

    NodeList result=null;
    try{
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!

        DocumentBuilder newBuilder = domFactory.newDocumentBuilder();
        Document newDoc = newBuilder.newDocument();

        Element root = newDoc.createElement("root");
        newDoc.appendChild(root);
        if(left!=null){
            for(int i=0;i<left.getLength();i++){
                Node tmp=(Node)left.item(i).cloneNode(true);
                newDoc.adoptNode(tmp);
                newDoc.getDocumentElement().appendChild(tmp);
                //root.appendChild(newDoc.importNode((Node)left.item(i), true));
            }
        }
        if(right!=null){
            for(int i=0;i<right.getLength();i++){
                Node tmp=(Node)right.item(i).cloneNode(true);
                newDoc.adoptNode(tmp);
                newDoc.getDocumentElement().appendChild(tmp);
                //root.appendChild(newDoc.importNode((Node)right.item(i), true));
            }
        }

        result=root.getChildNodes();
    } catch(ParserConfigurationException e){
        System.err.println(e);
    }

    return result;
}

In this code I'm trying to unite two NodeLists into one.

It works well, except the fact that after union, the nodes loses the context of their parent, ancestor, preceding-sibling etc... So if I'm trying to run evaluate on the result and use parent/ansector/preceding-sibling/etc axis on the result, it fails.

What should I do in order they won't lose it?

Thanks.

4

1 回答 1

1

一个节点只能存在于一个文档中。如果您希望复制的节点同时出现在两个文档中,那么您就不走运了。您只能在目标文档中创建一个新节点并将子节点和属性从旧节点移动到新节点。查看 Document::adoptNode(Node) 可能是最简单的方法。

于 2013-05-18T23:14:17.370 回答