This tutorial teaches how to read and differentiate different type of XML Nodes.
There are 3 important XML data parts.
There are 3 important XML data parts.
- Element - Elements have tags. In above example bookstore, book, title, author are elements
- Attribute - These are attributes for Elements. In above example category is attribute.
- Text - Simple text surrounded by tags
Program Flow :
- Read ROOT Element as Node
- If it is Text, go to 3rd step else go to 4th step.
- print text value
- If it is Element, print all attributes and list children and send them to 2nd step
XML Node Types :
Node | Node Type | Named Constant |
---|---|---|
Element | 1 | ELEMENT_NODE |
Attribute | 2 | ATTRIBUTE_NODE |
Text | 3 | TEXT_NODE |
JavaScript Code :
Here you can find JavaScript source code parse XML. In below code you can find some individual functions. Those are explained below
readNode : It will parse all type of XML nodes
trimSpace : This function removes all unwanted space from the XML
loadXMLDoc : This function is for loading XML document
var parseXml; var res = ''; if (window.DOMParser) { parseXml = function(xmlStr) { return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml"); }; } else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) { parseXml = function(xmlStr) { var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(xmlStr); return xmlDoc; }; } else { parseXml = function() { return null; } } var xmlDoc = parseXml(trimSpace(loadXMLDoc("books.xml"))); x=xmlDoc.documentElement; readNode(x); document.getElementById("result").innerHTML = res; function readNode(node) { res+=" <br/>"; res+=" (nodetype: " + node.nodeType + ") "; if(node.nodeType == 1) { res+="Nodename: " + node.nodeName; var y=node.childNodes; for(var i=0;i<y.length;i++) { readNode(y[i]); } } else if(node.nodeType == 2) { res+="Nodename: " + node.nodeName; } else if(node.nodeType == 3) { res+="Nodevalue: " + node.textContent+ ""; } res+=" <br/>"; } function trimSpace(val) { var lines = val.split('\n'); var out=''; for(var i = 0;i < lines.length;i++){ out += lines[i].trim(); } return out; } function loadXMLDoc(file) { 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",file,false); xmlhttp.send(); return xmlhttp.responseText; }
This comment has been removed by the author.
ReplyDeleteI love this. It is soo informative. Are you also searching for cheap assignment help we are the best solution for you. We are best known for delivering the best services to students without having to break the bank
ReplyDelete