在本章中,我们将研究XML DOM对象中的替换节点操作。众所周知,DOM中的所有内容都以称为节点的分层信息单元维护,替换节点提供了另一种更新这些指定节点或文本节点的方法。 以下是替换节点的两种方法。
replaceChild()方法replaceChild()用新节点替换指定的节点。 句法insertData()具有以下语法- Node replaceChild(Node newChild, Node oldChild) throws DOMException 哪里,
例下面的例子(replacenode_example.htm)解析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("/dom/node.xml"); x = xmlDoc.documentElement; z = xmlDoc.getElementsByTagName("FirstName"); document.write("<b>Content of FirstName element before replace operation</b><br>"); for (i=0;i<z.length;i++) { document.write(z[i].childNodes[0].nodeValue); document.write("<br>"); } //create a Employee element, FirstName element and a text node newNode = xmlDoc.createElement("Employee"); newTitle = xmlDoc.createElement("Name"); newText = xmlDoc.createTextNode("MS Dhoni"); //add the text node to the title node, newTitle.appendChild(newText); //add the title node to the book node newNode.appendChild(newTitle); y = xmlDoc.getElementsByTagName("Employee")[0] //replace the first book node with the new node x.replaceChild(newNode,y); z = xmlDoc.getElementsByTagName("FirstName"); document.write("<b>Content of FirstName element after replace operation</b><br>"); for (i = 0;i<z.length;i++) { document.write(z[i].childNodes[0].nodeValue); document.write("<br>"); } </script> </body> </html> 执行将此文件另存为serverpath上的replacenode_example.htm(此文件和node.xml应位于服务器中的同一路径上)。我们将得到如下所示的输出- Content of FirstName element before replace operation Tanmay Taniya Tanisha Content of FirstName element after replace operation Taniya Tanisha replaceData()方法replaceData()使用指定的字符串替换从指定的16位单元偏移量开始的字符。 句法replaceData()具有以下语法- void replaceData(int offset, int count, java.lang.String arg) throws DOMException 哪里
例下面的示例(replacedata_example.htm)将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("/dom/node.xml"); x = xmlDoc.getElementsByTagName("ContactNo")[0].childNodes[0]; document.write("<b>ContactNo before replace operation:</b> "+x.nodeValue); x.replaceData(1,5,"9999999"); document.write("<br>"); document.write("<b>ContactNo after replace operation:</b> "+x.nodeValue); </script> </body> </html> 在上面的示例中-
执行在服务器路径上将此文件另存为replacedata_example.htm(此文件和node.xml应在服务器中的同一路径上)。我们将得到如下所示的输出- ContactNo before replace operation: 1234567890 ContactNo after replace operation: 199999997890 |