XML DOM克隆节点

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

cloneNode()方法

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

语法

cloneNode()方法具有以下语法 -

Node cloneNode(boolean deep)
  • deep - 如果为true,则递归克隆指定节点下的子树; 如果为false,则仅克隆节点本身及其属性(如果它是元素的话)。
  • 此方法返回重复节点。

示例

以下示例(clonenode.html)将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(/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元素下的每个子元素。

执行结果

运行上面示例代码,得到以下结果 -