1 /**2 * Created by Administrator on 2015/4/4.3 */4 5 varXmlutil= (function () {6 varCreatedocument=function () {7 if(typeofArguments.callee.activeXString! = ' String '){8 varVersions=[' MSXML2. domdocument.6.0 ', ' MSXML2. domdocument.3.0 ', ' MSXML2. DOMDocument '],9 I,len;Ten for(i=0,len=versions.length;i<len;i++){ One Try{ A NewActiveXObject (Versions[i]); -arguments.callee.activexstring=Versions[i]; - Break; the}Catch(e) { - //Skip over - } - } + } - return NewActiveXObject (arguments.callee.activeXString); + }; A return { at //serializes an XML string into a Xmldom object -Parsexml:function(XML) { - varXmldom=NULL; - if(Domparser! = ' undefined '){ - varDomparser=NewDomparser (); -xmldom= domparser.parsefromstring (XML, ' Text/xml ')); in varErrorelment=xmldom.getelementsbytagname (' ParserError '); - if(errorelment.length>0){ to Throw NewError (' XML PARSER error: ' +errorelment[0].textcontent); + } -}Else if(typeofActiveXObject! = ' undefined '){ theXmldom=createdocument (); * xmldom.loadxml (XML); $ if(Xmldom.parseerror! = 0){Panax Notoginseng Throw NewError (' XML parsing error: ' +Xmldom.parseError.reason); - } the}Else{ + Throw NewError (' NO XML PARSER AVAILABLE '); A } the returnxmldom; + }, - //sequence the Xmldom object into an XML object $Serializexml:function(xmldom) { $ if(typeofXMLSerializer! = ' undefined '){ - return NewXMLSerializer (). serializetostring (XMLDOM); -}Else if(typeofXmldom.xml! = ' undefined '){ the returnXmldom.xml; -}Else{Wuyi Throw NewError (' Could not serialize XML DOM '); the } - } Wu } - About}());
Usage
1 var xmldom=xmlutil.parsexml (' <root><child/></root> '); 2 Console.log (XMLDOM); 3 console.log (Xmlutil.serializexml (XMLDOM));
javascript-processing XML