简体   繁体   English

如何将元素从现有文档添加到新文档?

[英]How do I add element from an existing document to a new document?

For my case, I need to take some nodes from the existing XML file and create a new document and add the all nodes that are in existing file. 就我而言,我需要从现有XML文件中提取一些节点,然后创建一个新文档,并添加现有文件中的所有节点。

How do I add element from an existing document to a new document? 如何将元素从现有文档添加到新文档?

Likely problem is that you tried to insert node to the target document without importing it. 可能的问题是您尝试将节点插入到目标文档中而不导入它。 Importing node to target document is done via Document.importNode . 通过Document.importNode将节点导入到目标文档。 Code is roughly as follows, of course exact location in target document should be changed specific to you application: 代码大致如下,当然,应针对您的应用程序更改目标文档中的确切位置:

    NodeList list ...
    for(int i=0; i < list.getLength(); i++){
        Node nodeToImport = list.item(i);
        Node importedNode = targetDocument.importNode(nodeToImport, true);
        targetDocument.getDocumentElement().appendChild(importedNode);
    }

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

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