XML DOM删除节点操作的方法
发布时间:2023-09-21 11:18:41 所属栏目:教程 来源:
导读:我们将学习XML DOM删除节点的操作。删除节点操作是指从文档中删除指定的节点。实现此操作以移除诸如文本节点,元素节点或属性节点之类的节点。
以下是用于删除节点操作的方法 -
removeChild()方法
removeAttrib
以下是用于删除节点操作的方法 -
removeChild()方法
removeAttrib
我们将学习XML DOM删除节点的操作。删除节点操作是指从文档中删除指定的节点。实现此操作以移除诸如文本节点,元素节点或属性节点之类的节点。 以下是用于删除节点操作的方法 - removeChild()方法 removeAttribute()方法 1. removeChild()方法 removeChild()方法从子列表中删除oldChild指示的子节点,并将其返回。 删除子节点等同于删除文本节点。 因此,删除子节点会删除与其关联的文本节点。 语法 使用removeChild()方法的语法如下 - Node removeChild(Node oldChild) throws DOMException 其中,oldChild - 是要删除的节点。此方法返回已删除的节点。 示例1 - 删除当前节点 以下示例(remove_curtnode.html)将XML文档(node.xml)解析为XML DOM对象,并从父节点中删除指定的节点<ContactNo>。 <!DOCTYPE html> <html> <head> <Meta charset=utf-8> <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); document.write(<b>在删除操作之前,总共有ContactNo元素: </b>); document.write(xmlDoc.getElementsByTagName(ContactNo).length); document.write(<br>); x = xmlDoc.getElementsByTagName(ContactNo)[0]; x.parentNode.removeChild(x); document.write(<b>在删除操作之后,总共有ContactNo元素: </b>); document.write(xmlDoc.getElementsByTagName(ContactNo).length); </script> </body> </html> 在上面的例子中 - x = xmlDoc.getElementsByTagName(ContactNo)[0]获取索引为0的元素<ContactNo>。 x.parentNode.removeChild(x);从父节点中删除索引为0的元素<ContactNo>。 2. removeAttribute()方法 removeAttribute()方法按名称删除元素的属性。 语法 使用removeAttribute()的语法如下 - void removeAttribute(java.lang.String name) throws DOMException 其中,name - 要删除的属性的名称。 示例 以下示例(remove_elementattribute.html)将XML文档(node.xml)解析为XML DOM对象,并删除指定的属性节点。 <!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'); document.write(x[1].getAttribute('category')); document.write(<br>); x[1].removeAttribute('category'); document.write(x[1].getAttribute('category')); </script> </body> </html> 在上面示例代码中 − document.write(x[1].getAttribute('category')); − 调用在第一个位置索引的category属性的值。 x[1].removeAttribute('category'); − 删除属性的值。 (编辑:汽车网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |