在本章中,我们将研究如何更改XML DOM对象中节点的值.节点值可以更改为 :
var value = node.nodeValue;
如果 node 是属性,那么 value 变量将是属性的值;如果节点是 Text 节点,则它将是文本内容;如果节点是元素,它将 null .
以下部分将演示节点值设置对于每个节点类型(属性,文本节点和元素).
以下所有示例中使用的 node.xml 如下 :
<Company> <Employee category = "Technical"> <FirstName>Tanmay</FirstName> <LastName>Patil</LastName> <ContactNo>1234567890</ContactNo> <Email>tanmaypatil@xyz.com</Email> </Employee> <Employee category = "Non-Technical"> <FirstName>Taniya</FirstName> <LastName>Mishra</LastName> <ContactNo>1234667898</ContactNo> <Email>taniyamishra@xyz.com</Email> </Employee> <Employee category = "Management"> <FirstName>Tanisha</FirstName> <LastName>Sharma</LastName> <ContactNo>1234562350</ContactNo> <Email>tanishasharma@xyz.com</Email> </Employee> </Company>
当我们说Node元素的更改值时,我们的意思是编辑文本元素的内容(也称为文本节点).下面的示例演示如何更改元素的文本节点.
以下示例(set_text_node_example.htm)解析XML文档( node.xml )到XML DOM对象并更改元素文本节点的值.在这种情况下,每个员工的电子邮件到 support@xyz.com 并打印值.
<!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("https://img01.yuandaxia.cn/Content/img/tutorials/dom/node.xml"); x = xmlDoc.getElementsByTagName("Email"); for(i = 0;i<x.length;i++) { x[i].childNodes[0].nodeValue = "support@xyz.com"; document.write(i+'); document.write(x[i].childNodes[0].nodeValue); document.write('<br>'); } </script> </body> </html>
将此文件保存为服务器路径上的 set_text_node_example.htm 文件和 node.xml 应位于服务器的同一路径上.您将收到以下输出 :
0)support@xyz.com 1)support@xyz.com 2)support@xyz.com
以下示例演示如何更改元素的属性节点.
以下示例(set_attribute_example.htm)解析XML文档( node.xml )到XML DOM对象中并更改元素属性节点的值.在这种情况下,每个员工的类别分别为 admin-0,admin-1,admin-2 并打印值.
<!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("https://img01.yuandaxia.cn/Content/img/tutorials/dom/node.xml"); x = xmlDoc.getElementsByTagName("Employee"); for(i = 0 ;i<x.length;i++){ newcategory = x[i].getAttributeNode('category'); newcategory.nodeValue = "admin-"+i; document.write(i+'); document.write(x[i].getAttributeNode('category').nodeValue); document.write('<br>'); } </script> </body> </html>
将此文件保存为服务器路径上的 set_node_attribute_example.htm (此文件和 node.xml 应位于服务器的同一路径上.结果如下:
0)admin-0 1)admin-1 2)admin -2