
- XML DOM 基礎
- XML DOM - 首頁
- XML DOM - 概述
- XML DOM - 模型
- XML DOM - 節點
- XML DOM - 節點樹
- XML DOM - 方法
- XML DOM - 載入
- XML DOM - 遍歷
- XML DOM - 導航
- XML DOM - 訪問
- XML DOM 操作
- XML DOM - 獲取節點
- XML DOM - 設定節點
- XML DOM - 建立節點
- XML DOM - 新增節點
- XML DOM - 替換節點
- XML DOM - 刪除節點
- XML DOM - 克隆節點
- XML DOM 物件
- DOM - 節點物件
- DOM - NodeList 物件
- DOM - NamedNodeMap 物件
- DOM - DOMImplementation
- DOM - DocumentType 物件
- DOM - ProcessingInstruction
- DOM - Entity 物件
- DOM - EntityReference 物件
- DOM - Notation 物件
- DOM - Element 物件
- DOM - Attribute 物件
- DOM - CDATASection 物件
- DOM - Comment 物件
- DOM - XMLHttpRequest 物件
- DOM - DOMException 物件
- XML DOM 有用資源
- XML DOM - 快速指南
- XML DOM - 有用資源
- XML DOM - 討論
XML DOM - 克隆節點
本章將討論 XML DOM 物件上的克隆節點操作。克隆節點操作用於建立指定節點的副本。cloneNode() 用於此操作。
cloneNode()
此方法返回此節點的副本,即充當節點的通用複製建構函式。副本節點沒有父節點(parentNode 為 null)並且沒有使用者資料。
語法
cloneNode() 方法具有以下語法:
Node cloneNode(boolean deep)
deep - 如果為 true,則遞迴克隆指定節點下的子樹;如果為 false,則只克隆節點本身(及其屬性,如果它是 Element)。
此方法返回重複的節點。
示例
以下示例 (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("/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 元素被完整克隆。
廣告