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元素下的每個子元素。

執行結果

運行上面示例代碼,得到以下結果 -

XML