XML DOM - 克隆节点
在本章中,我们将讨论 XML DOM 对象上的 克隆节点 操作。克隆节点操作用于创建指定节点的副本。cloneNode() 用于此操作。
cloneNode()
此方法返回此节点的副本,即用作节点的通用复制构造函数。重复节点没有父节点(parentNode 为 null)且没有用户数据。
语法
cloneNode() 方法具有以下语法 −
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("/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 元素已被完全克隆。

