/* * Parse XML documents in pure JS (compatible with various browsers) */ Function parseXMLDOM (){ Var _ browserType = ""; Var _ xmlFile = ""; Var _ XmlDom = null; Return { "GetBrowserType": function (){ Return _ browserType; }, "SetBrowserType": function (browserType ){ _ BrowserType = browserType; }, "GetXmlFile": function (){ Return _ xmlFile; }, "SetXmlFile": function (xmlFile ){ _ XmlFile = xmlFile; }, "GetXmlDom": function (){ Return _ XmlDom; }, "SetXmlDom": function (XmlDom ){ _ XmlDom = XmlDom; }, "GetBrowserType": function (){ Var browserType = ""; If (navigator. userAgent. indexOf ("MSIE ")! =-1 ){ BrowserType = "IE "; } Else if (navigator. userAgent. indexOf ("Chrome ")! =-1 ){ BrowserType = "Chrome "; } Else if (navigator. userAgent. indexOf ("Firefox ")! =-1 ){ BrowserType = "Firefox" } Return browserType; }, "CreateXmlDom": function (xmlDom ){ If (this. getBrowserType () = "IE") {// IE browser XmlDom = new ActiveXObject ('Microsoft. XMLDOM '); XmlDom. async = false; XmlDom. load (this. getXmlFile ()); } Else { Var xmlhttp = new XMLHttpRequest (); Xmlhttp. open ("GET", this. getXmlFile (), false ); Xmlhttp. send (null ); XmlDom = xmlhttp. responseXML; } Return xmlDom; }, "ParseXMLDOMInfo": function (){ Var xmlDom = this. getXmlDom (); If (this. getBrowserType () = "IE "){ Var bookObj = xmlDom. selectNodes ("books/book "); If (typeof (bookObj )! = "Undifined "){ Var strHtml = ""; For (var I = 0; I <bookObj. length; I ++ ){ StrHtml + = bookObj [I]. selectSingleNode ("isbn"). text; StrHtml + = ""; StrHtml + = bookObj [I]. selectSingleNode ("price"). text; StrHtml + = ""; StrHtml + = bookObj [I]. selectSingleNode ("title"). text; If (I! = BookObj. length-1 ){ StrHtml + = "<br> "; } } } } Else { Var book = xmlDom. getElementsByTagName ("book "); Var strHtml = ""; For (var I = 0; I <book. length; I ++ ){ StrHtml + = book [I]. getElementsByTagName ("isbn") [0]. textContent; StrHtml + = ""; StrHtml + = ""; StrHtml + = book [I]. getElementsByTagName ("price") [0]. textContent; StrHtml + = ""; StrHtml + = book [I]. getElementsByTagName ("title") [0]. textContent; If (I! = Book. length-1 ){ StrHtml + = "<br> "; } } } Document. getElementById ("msg"). innerHTML = strHtml; } } } Window. onload = function (){ Var parseObj = new parseXMLDOM (); // Set the browser type ParseObj. setBrowserType (parseObj. getBrowserType ()); // Set the file path ParseObj. setXmlFile ("test. xml "); // Create XMLDOM ParseObj. setXmlDom (parseObj. createXmlDom (null )); // Parse XMLDOM ParseObj. parseXMLDOMInfo (); } |