XML DOM - 克隆节点

在本章中,我们将讨论XML DOM对象上的 Clone Node 操作.克隆节点操作用于创建指定节点的副本. cloneNode()用于此操作.

cloneNode()

此方法返回此节点的副本,即,用作节点的通用复制构造函数.重复节点没有父节点(parentNode为空),没有用户数据.

语法

cloneNode() method具有以下语法 :

Node cloneNode(boolean deep)

  • deep : 如果为true,则递归地克隆指定节点下的子树;如果为false,则仅克隆节点本身(及其属性,如果它是元素).

  • 此方法返回重复节点.

示例

以下示例(clonenode_example.htm)解析XML文档( node.xml )转换为XML DOM对象,并创建第一个 Employee 元素.

<!DOCTYPE html>
<html>
   <head>
      <script>
         function loadXMLDoc(filename) {
            if (window.XMLHttpRequest) {
               xhttp = new XMLHttpRequest();
            } else // code for IE5 and IE6 {
               xhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xhttp.open("GET",filename,false);
            xhttp.send();
            return xhttp.responseXML;
         }
      </script>
   </head>
   <body>
      <script>
         xmlDoc = loadXMLDoc("https://img01.yuandaxia.cn/Content/img/tutorials/dom/node.xml");

         x = xmlDoc.getElementsByTagName('Employee')[0];
         clone_node = x.cloneNode(true);
         xmlDoc.documentElement.appendChild(clone_node);

         firstname = xmlDoc.getElementsByTagName("FirstName");
         lastname = xmlDoc.getElementsByTagName("LastName");
	 contact = xmlDoc.getElementsByTagName("ContactNo");
	 email = xmlDoc.getElementsByTagName("Email");
         for (i = 0;i < firstname.length;i++) {
            document.write(firstname[i].childNodes[0].nodeValue+'  
               '+lastname[i].childNodes[0].nodeValue+',  
               '+contact[i].childNodes[0].nodeValue+',  '+email[i].childNodes[0].nodeValue);
            document.write("<br>");
         }
      </script>
   </body>
</html>

正如您在上面的示例中所看到的,我们已将 cloneNode()参数设置为 true .因此,复制或克隆 Employee 元素下的每个子元素.

执行

将此文件另存为 clonenode_example.htm 在服务器路径上(此文件和node.xml应位于服务器的同一路径上).我们将得到如下所示的输出 :

Tanmay Patil, 1234567890, tanmaypatil@xyz.com
Taniya Mishra, 1234667898, taniyamishra@xyz.com
Tanisha Sharma, 1234562350, tanishasharma@xyz.com
Tanmay Patil, 1234567890, tanmaypatil@xyz.com

您会注意到第一个 Employee 元素已完全克隆.