The createElementNS() method us used to create an element with a namespace.
Syntax for createElementNS() method:
createElementNS(ns, name);
Where,
- ns is namespace in which element is to be created;
- name is the name of the element node to be created.
The example below adds an element node with a namespace to the XML document . The createElementNS() returns the element node created in the namespace passed.
Example with createElementNS() method
<!DOCTYPE html>
<html>
<body>
<script>
function loadFile(name){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",name,false);
xmlhttp.send();
return xmlhttp.responseXML;
}
xmlDoc = loadFile("element.xml");
xd = xmlDoc.documentElement;
newEle = xmlDoc.createElementNS("edu", "school");
newTxt = xmlDoc.createTextNode("Christ College");
newEle .appendChild(newTxt);
d = xmlDoc.getElementsByTagName("students")[0];
d.appendChild(newEle);
d = xmlDoc.getElementsByTagName("students");
for(j=0; j<d.length; j++){
c = d[j].childNodes;
for(i=0; i< c.length; i++){
if(c[i].nodeType != 3){
document.write("NodeName : " + c[i].nodeName);
document.write(" NodeType : " + c[i].nodeType);
document.write(" NodeValue : " + c[i].childNodes[0].nodeValue);
document.write(" Namespace : " + c[i].namespaceURI + "<br/>");
}
}
}
</script>
</body>
</html>
Output of the example above:
NodeName : name NodeType : 1 NodeValue : Roshni Namespace : null
NodeName : class NodeType : 1 NodeValue : 3rd grade Namespace : null
NodeName : school NodeType : 1 NodeValue : Christ College Namespace : edu
Comments
No comments have been made yet.
Please login to leave a comment. Login now