- 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 - 节点列表对象
- DOM - 命名节点映射对象
- DOM - DOMI 实现
- DOM - 文档类型对象
- DOM - 处理指令
- DOM-实体对象
- DOM - 实体引用对象
- DOM - 表示法对象
- DOM - 元素对象
- DOM - 属性对象
- DOM - CDATASection 对象
- DOM - 评论对象
- DOM - XMLHttpRequest 对象
- DOM - DOMException 对象
- XML DOM 有用的资源
- XML DOM - 快速指南
- XML DOM - 有用的资源
- XML DOM - 讨论
XML DOM - 克隆节点
在本章中,我们将讨论XML DOM 对象上的克隆节点操作。克隆节点操作用于创建指定节点的重复副本。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元素已完全克隆。