XML DOM createElementNS() 方法
定义和用法
createElementNS()
方法创建带命名空间的元素节点。
该方法返回 Element 对象。
语法
createElementNS(ns,name)
参数 | 描述 |
---|---|
ns | 字符串,规定元素节点的命名空间名称。 |
name | 字符串,规定元素节点名称。 |
实例
下面的代码将 "books.xml" 加载到 xmlDoc 中,并向每个
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); function myFunction(xml) { var x, y, z, i, newel, newtext, xmlDoc, txt; xmlDoc = xml.responseXML; txt = ""; x = xmlDoc.getElementsByTagName("book"); // 使用命名空间和文本节点创建元素节点 for (i = 0; i < x.length; i++) { newel = xmlDoc.createElementNS("p", "edition"); newtext = xmlDoc.createTextNode("First"); newel.appendChild(newtext); x[i].appendChild(newel); } // 输出所有 title 和 edition y = xmlDoc.getElementsByTagName("title"); z = xmlDoc.getElementsByTagNameNS("p","edition"); for (i = 0; i < y.length; i++) { txt += y[i].childNodes[0].nodeValue + " - " + z[i].childNodes[0].nodeValue + " édition." + "Namespace: " + z[i].namespaceURI + "<br>"; } document.getElementById("demo").innerHTML = txt; }