- 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 元素被完整克隆。
广告