This article mainly introduces the methods for parsing XML documents and XML strings using javascript and the specific code. If you need it, you can refer to it. I have written a link to "using jquery to parse XML" at http://www.jb51.net/article/54842.htm. the previous article details the method for converting jquery and strings. Here I will focus on javascript to operate xml.
The Code is as follows:
Var XMLHttp = null; if (window. XMLHttpRequest) {// modern browser XMLHttp = new XMLHttpRequest ();} else if (window. activeXObject) {XMLHttp = new ActiveXObject ("Microsoft. XMLHTTP "); // IE5/IE6} if (XMLHttp! = Null) {XMLHttp. onreadystatechange = function () {if (XMLHttp. readyState = 4) {if (XMLHttp. status = 200 | XMLHttp. status = 304) {// var XMLDom = XMLHttp. responseXML; // parse the XML document var XMLDoc = XMLHttp. responseText; // parse the XML string var XMLDom = (new DOMParser ()). parseFromString (XMLDoc, "text/xml"); // write the asynchronous code to the console. log (XMLDom); console. log ("world"); // The following message appears: world }}; XMLHttp. open ("get", "test1.xml", true); XMLHttp. send (); // write the non-asynchronous code to the console. log ("hello"); // hello appears first}
Step 1: Create XMLHTTPREQUEST:
Var XMLHttp = null; if (window. XMLHttpRequest) {// modern browser XMLHttp = new XMLHttpRequest ();} else if (window. activeXObject) {XMLHttp = new ActiveXObject ("Microsoft. XMLHTTP "); // IE5/IE6}
Step 2: Check ONREADYSTATECHANGE (not asynchronous ):
If (XMLHttp! = Null) {XMLHttp. onreadystatechange = function () {if (XMLHttp. readyState = 4) {if (XMLHttp. status = 200 | XMLHttp. status = 304) {// write the asynchronous code here }}; XMLHttp. open ("get", "test1.xml", true); XMLHttp. send (); // write non-asynchronous code here}
Step 3: parse the XML document or string (asynchronous ):
XMLHttp. onreadystatechange = function () {if (XMLHttp. readyState = 4) {if (XMLHttp. status = 200 | XMLHttp. status = 304) {// var XMLDom = XMLHttp. responseXML; // parse the XML document var XMLDoc = XMLHttp. responseText; // parse the XML string var XMLDom = (new DOMParser ()). parseFromString (XMLDoc, "text/xml"); // write the asynchronous code to the console. log (XMLDom );}}};
Step 4: parse the XML document or string (non-asynchronous ):
If (XMLHttp! = Null) {// XMLHttp. onreadystatechange = function () {// if (XMLHttp. readyState = 4) {// if (XMLHttp. status = 200 | XMLHttp. status = 304) {}//} //}; XMLHttp. open ("get", "test1.xml", false); XMLHttp. send (); // write non-asynchronous code here // var XMLDom = XMLHttp. responseXML; // parse the XML document var XMLDoc = XMLHttp. responseText; // parse the XML string var XMLDom = (new DOMParser ()). parseFromString (XMLDoc, "text/xml"); // write the asynchronous code to the console. log (XMLDom );}