Best JavaScript code snippet using playwright-internal
jkl-parsexml.js
Source: jkl-parsexml.js
1// ================================================================2// jkl-parsexml.js ---- JavaScript Kantan Library for Parsing XML3// Copyright 2005-2007 Kawasaki Yusuke <u-suke@kawa.net>4// http://www.kawa.net/works/js/jkl/parsexml.html5// ================================================================6// v0.01 2005/05/18 first release7// v0.02 2005/05/20 Opera 8.0beta may be abailable but somtimes crashed8// v0.03 2005/05/20 overrideMimeType( "text/xml" );9// v0.04 2005/05/21 class variables: REQUEST_TYPE, RESPONSE_TYPE10// v0.05 2005/05/22 use Msxml2.DOMDocument.5.0 for GET method on IE611// v0.06 2005/05/22 CDATA_SECTION_NODE12// v0.07 2005/05/23 use Microsoft.XMLDOM for GET method on IE613// v0.10 2005/10/11 new function: JKL.ParseXML.HTTP.responseText()14// v0.11 2005/10/13 new sub class: JKL.ParseXML.Text, JSON and DOM.15// v0.12 2005/10/14 new sub class: JKL.ParseXML.CSV and CSVmap.16// v0.13 2005/10/28 bug fixed: TEXT_NODE regexp for white spaces17// v0.14 2005/11/06 bug fixed: TEXT_NODE regexp at Safari18// v0.15 2005/11/08 bug fixed: JKL.ParseXML.CSV.async() method19// v0.16 2005/11/15 new sub class: LoadVars, and UTF-8 text on Safari20// v0.18 2005/11/16 improve: UTF-8 text file on Safari21// v0.19 2006/02/03 use XMLHTTPRequest instead of ActiveX on IE7,iCab22// v0.20 2006/03/22 (skipped)23// v0.21 2006/11/30 use ActiveX again on IE724// v0.22 2007/01/04 JKL.ParseXML.JSON.parseResponse() updated25// ================================================================26if ( typeof(JKL) == 'undefined' ) JKL = function() {};27// ================================================================28// class: JKL.ParseXML 29JKL.ParseXML = function ( url, query, method ) {30 // debug.print( "new JKL.ParseXML( '"+url+"', '"+query+"', '"+method+"' );" );31 this.http = new JKL.ParseXML.HTTP( url, query, method, false );32 return this;33};34// ================================================================35// class variables36JKL.ParseXML.VERSION = "0.22";37JKL.ParseXML.MIME_TYPE_XML = "text/xml";38JKL.ParseXML.MAP_NODETYPE = [39 "",40 "ELEMENT_NODE", // 141 "ATTRIBUTE_NODE", // 242 "TEXT_NODE", // 343 "CDATA_SECTION_NODE", // 444 "ENTITY_REFERENCE_NODE", // 545 "ENTITY_NODE", // 646 "PROCESSING_INSTRUCTION_NODE", // 747 "COMMENT_NODE", // 848 "DOCUMENT_NODE", // 949 "DOCUMENT_TYPE_NODE", // 1050 "DOCUMENT_FRAGMENT_NODE", // 1151 "NOTATION_NODE" // 1252];53// ================================================================54// define callback function (ajax)55JKL.ParseXML.prototype.async = function ( func, args ) {56 this.callback_func = func; // callback function57 this.callback_arg = args; // first argument58};59JKL.ParseXML.prototype.onerror = function ( func, args ) {60 this.onerror_func = func; // callback function61};62// ================================================================63// method: parse()64// return: parsed object65// Download a file from remote server and parse it.66JKL.ParseXML.prototype.parse = function () {67 if ( ! this.http ) return;68 // set onerror call back 69 if ( this.onerror_func ) {70 this.http.onerror( this.onerror_func );71 }72 if ( this.callback_func ) { // async mode73 var copy = this;74 var proc = function() {75 if ( ! copy.http ) return;76 var data = copy.parseResponse();77 copy.callback_func( data, copy.callback_arg ); // call back78 };79 this.http.async( proc );80 }81 this.http.load();82 if ( ! this.callback_func ) { // sync mode83 var data = this.parseResponse();84 return data;85 }86};87// ================================================================88// every child/children into array89JKL.ParseXML.prototype.setOutputArrayAll = function () {90 this.setOutputArray( true );91}92// a child into scalar, children into array93JKL.ParseXML.prototype.setOutputArrayAuto = function () {94 this.setOutputArray( null );95}96// every child/children into scalar (first sibiling only)97JKL.ParseXML.prototype.setOutputArrayNever = function () {98 this.setOutputArray( false );99}100// specified child/children into array, other child/children into scalar101JKL.ParseXML.prototype.setOutputArrayElements = function ( list ) {102 this.setOutputArray( list );103}104// specify how to treate child/children into scalar/array105JKL.ParseXML.prototype.setOutputArray = function ( mode ) {106 if ( typeof(mode) == "string" ) {107 mode = [ mode ]; // string into array108 }109 if ( mode && typeof(mode) == "object" ) {110 if ( mode.length < 0 ) {111 mode = false; // false when array == [] 112 } else {113 var hash = {};114 for( var i=0; i<mode.length; i++ ) {115 hash[mode[i]] = true;116 }117 mode = hash; // array into hashed array118 if ( mode["*"] ) {119 mode = true; // true when includes "*"120 }121 } 122 } 123 this.usearray = mode;124}125// ================================================================126// method: parseResponse()127JKL.ParseXML.prototype.parseResponse = function () {128 var root = this.http.documentElement();129 var data = this.parseDocument( root );130 return data;131}132// ================================================================133// convert from DOM root node to JavaScript Object 134// method: parseElement( rootElement )135JKL.ParseXML.prototype.parseDocument = function ( root ) {136 // debug.print( "parseDocument: "+root );137 if ( ! root ) return;138 var ret = this.parseElement( root ); // parse root node139 // debug.print( "parsed: "+ret );140 if ( this.usearray == true ) { // always into array141 ret = [ ret ];142 } else if ( this.usearray == false ) { // always into scalar143 //144 } else if ( this.usearray == null ) { // automatic145 //146 } else if ( this.usearray[root.nodeName] ) { // specified tag147 ret = [ ret ];148 }149 var json = {};150 json[root.nodeName] = ret; // root nodeName151 return json;152};153// ================================================================154// convert from DOM Element to JavaScript Object 155// method: parseElement( element )156JKL.ParseXML.prototype.parseElement = function ( elem ) {157 // debug.print( "nodeType: "+JKL.ParseXML.MAP_NODETYPE[elem.nodeType]+" <"+elem.nodeName+">" );158 // COMMENT_NODE159 if ( elem.nodeType == 7 ) {160 return;161 }162 // TEXT_NODE CDATA_SECTION_NODE163 if ( elem.nodeType == 3 || elem.nodeType == 4 ) {164 // var bool = elem.nodeValue.match( /[^\u0000-\u0020]/ );165 var bool = elem.nodeValue.match( /[^\x00-\x20]/ ); // for Safari166 if ( bool == null ) return; // ignore white spaces167 // debug.print( "TEXT_NODE: "+elem.nodeValue.length+ " "+bool );168 return elem.nodeValue;169 }170 var retval;171 var cnt = {};172 // parse attributes173 if ( elem.attributes && elem.attributes.length ) {174 retval = {};175 for ( var i=0; i<elem.attributes.length; i++ ) {176 var key = elem.attributes[i].nodeName;177 if ( typeof(key) != "string" ) continue;178 var val = elem.attributes[i].nodeValue;179 if ( ! val ) continue;180 if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;181 cnt[key] ++;182 this.addNode( retval, key, cnt[key], val );183 }184 }185 // parse child nodes (recursive)186 if ( elem.childNodes && elem.childNodes.length ) {187 var textonly = true;188 if ( retval ) textonly = false; // some attributes exists189 for ( var i=0; i<elem.childNodes.length && textonly; i++ ) {190 var ntype = elem.childNodes[i].nodeType;191 if ( ntype == 3 || ntype == 4 ) continue;192 textonly = false;193 }194 if ( textonly ) {195 if ( ! retval ) retval = "";196 for ( var i=0; i<elem.childNodes.length; i++ ) {197 retval += elem.childNodes[i].nodeValue;198 }199 } else {200 if ( ! retval ) retval = {};201 for ( var i=0; i<elem.childNodes.length; i++ ) {202 var key = elem.childNodes[i].nodeName;203 if ( typeof(key) != "string" ) continue;204 var val = this.parseElement( elem.childNodes[i] );205 if ( ! val ) continue;206 if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;207 cnt[key] ++;208 this.addNode( retval, key, cnt[key], val );209 }210 }211 }212 return retval;213};214// ================================================================215// method: addNode( hash, key, count, value )216JKL.ParseXML.prototype.addNode = function ( hash, key, cnts, val ) {217 if ( this.usearray == true ) { // into array218 if ( cnts == 1 ) hash[key] = [];219 hash[key][hash[key].length] = val; // push220 } else if ( this.usearray == false ) { // into scalar221 if ( cnts == 1 ) hash[key] = val; // only 1st sibling222 } else if ( this.usearray == null ) {223 if ( cnts == 1 ) { // 1st sibling224 hash[key] = val;225 } else if ( cnts == 2 ) { // 2nd sibling226 hash[key] = [ hash[key], val ];227 } else { // 3rd sibling and more228 hash[key][hash[key].length] = val;229 }230 } else if ( this.usearray[key] ) {231 if ( cnts == 1 ) hash[key] = [];232 hash[key][hash[key].length] = val; // push233 } else {234 if ( cnts == 1 ) hash[key] = val; // only 1st sibling235 }236};237// ================================================================238// class: JKL.ParseXML.Text 239JKL.ParseXML.Text = function ( url, query, method ) {240 // debug.print( "new JKL.ParseXML.Text( '"+url+"', '"+query+"', '"+method+"' );" );241 this.http = new JKL.ParseXML.HTTP( url, query, method, true );242 return this;243};244JKL.ParseXML.Text.prototype.parse = JKL.ParseXML.prototype.parse;245JKL.ParseXML.Text.prototype.async = JKL.ParseXML.prototype.async;246JKL.ParseXML.Text.prototype.onerror = JKL.ParseXML.prototype.onerror;247JKL.ParseXML.Text.prototype.parseResponse = function () {248 var data = this.http.responseText();249 return data;250}251// ================================================================252// class: JKL.ParseXML.JSON253JKL.ParseXML.JSON = function ( url, query, method ) {254 // debug.print( "new JKL.ParseXML.JSON( '"+url+"', '"+query+"', '"+method+"' );" );255 this.http = new JKL.ParseXML.HTTP( url, query, method, true );256 return this;257};258JKL.ParseXML.JSON.prototype.parse = JKL.ParseXML.prototype.parse;259JKL.ParseXML.JSON.prototype.async = JKL.ParseXML.prototype.async;260JKL.ParseXML.JSON.prototype.onerror = JKL.ParseXML.prototype.onerror;261JKL.ParseXML.JSON.prototype.parseResponse = function () {262 var text = this.http.responseText();263 // http://www.antimon2.atnifty.com/2007/01/jklparsexmljson.html264 if ( typeof(text) == 'undefined' ) return;265 if ( ! text.length ) return;266 var data = eval( "("+text+")" );267 return data;268}269// ================================================================270// class: JKL.ParseXML.DOM271JKL.ParseXML.DOM = function ( url, query, method ) {272 // debug.print( "new JKL.ParseXML.DOM( '"+url+"', '"+query+"', '"+method+"' );" );273 this.http = new JKL.ParseXML.HTTP( url, query, method, false );274 return this;275};276JKL.ParseXML.DOM.prototype.parse = JKL.ParseXML.prototype.parse;277JKL.ParseXML.DOM.prototype.async = JKL.ParseXML.prototype.async;278JKL.ParseXML.DOM.prototype.onerror = JKL.ParseXML.prototype.onerror;279JKL.ParseXML.DOM.prototype.parseResponse = function () {280 var data = this.http.documentElement();281 return data;282}283// ================================================================284// class: JKL.ParseXML.CSV285JKL.ParseXML.CSV = function ( url, query, method ) {286 // debug.print( "new JKL.ParseXML.CSV( '"+url+"', '"+query+"', '"+method+"' );" );287 this.http = new JKL.ParseXML.HTTP( url, query, method, true );288 return this;289};290JKL.ParseXML.CSV.prototype.parse = JKL.ParseXML.prototype.parse;291JKL.ParseXML.CSV.prototype.async = JKL.ParseXML.prototype.async;292JKL.ParseXML.CSV.prototype.onerror = JKL.ParseXML.prototype.onerror;293JKL.ParseXML.CSV.prototype.parseResponse = function () {294 var text = this.http.responseText();295 var data = this.parseCSV( text );296 return data;297}298JKL.ParseXML.CSV.prototype.parseCSV = function ( text ) {299 text = text.replace( /\r\n?/g, "\n" ); // new line character300 var pos = 0;301 var len = text.length;302 var table = [];303 while( pos<len ) {304 var line = [];305 while( pos<len ) {306 if ( text.charAt(pos) == '"' ) { // "..." quoted column307 var nextquote = text.indexOf( '"', pos+1 );308 while ( nextquote<len && nextquote > -1 ) {309 if ( text.charAt(nextquote+1) != '"' ) {310 break; // end of column311 }312 nextquote = text.indexOf( '"', nextquote+2 );313 }314 if ( nextquote < 0 ) {315 // unclosed quote316 } else if ( text.charAt(nextquote+1) == "," ) { // end of column317 var quoted = text.substr( pos+1, nextquote-pos-1 );318 quoted = quoted.replace(/""/g,'"');319 line[line.length] = quoted;320 pos = nextquote+2;321 continue;322 } else if ( text.charAt(nextquote+1) == "\n" || // end of line323 len==nextquote+1 ) { // end of file324 var quoted = text.substr( pos+1, nextquote-pos-1 );325 quoted = quoted.replace(/""/g,'"');326 line[line.length] = quoted;327 pos = nextquote+2;328 break;329 } else {330 // invalid column331 }332 }333 var nextcomma = text.indexOf( ",", pos );334 var nextnline = text.indexOf( "\n", pos );335 if ( nextnline < 0 ) nextnline = len;336 if ( nextcomma > -1 && nextcomma < nextnline ) {337 line[line.length] = text.substr( pos, nextcomma-pos );338 pos = nextcomma+1;339 } else { // end of line340 line[line.length] = text.substr( pos, nextnline-pos );341 pos = nextnline+1;342 break;343 }344 }345 if ( line.length >= 0 ) {346 table[table.length] = line; // push line347 }348 }349 if ( table.length < 0 ) return; // null data350 return table;351};352// ================================================================353// class: JKL.ParseXML.CSVmap354JKL.ParseXML.CSVmap = function ( url, query, method ) {355 // debug.print( "new JKL.ParseXML.CSVmap( '"+url+"', '"+query+"', '"+method+"' );" );356 this.http = new JKL.ParseXML.HTTP( url, query, method, true );357 return this;358};359JKL.ParseXML.CSVmap.prototype.parse = JKL.ParseXML.prototype.parse;360JKL.ParseXML.CSVmap.prototype.async = JKL.ParseXML.prototype.async;361JKL.ParseXML.CSVmap.prototype.onerror = JKL.ParseXML.prototype.onerror;362JKL.ParseXML.CSVmap.prototype.parseCSV = JKL.ParseXML.CSV.prototype.parseCSV;363JKL.ParseXML.CSVmap.prototype.parseResponse = function () {364 var text = this.http.responseText();365 var source = this.parseCSV( text );366 if ( ! source ) return;367 if ( source.length < 0 ) return;368 var title = source.shift(); // first line as title369 var data = [];370 for( var i=0; i<source.length; i++ ) {371 var hash = {};372 for( var j=0; j<title.length && j<source[i].length; j++ ) {373 hash[title[j]] = source[i][j]; // array to map374 }375 data[data.length] = hash; // push line376 }377 return data;378}379// ================================================================380// class: JKL.ParseXML.LoadVars381JKL.ParseXML.LoadVars = function ( url, query, method ) {382 // debug.print( "new JKL.ParseXML.LoadVars( '"+url+"', '"+query+"', '"+method+"' );" );383 this.http = new JKL.ParseXML.HTTP( url, query, method, true );384 return this;385};386JKL.ParseXML.LoadVars.prototype.parse = JKL.ParseXML.prototype.parse;387JKL.ParseXML.LoadVars.prototype.async = JKL.ParseXML.prototype.async;388JKL.ParseXML.LoadVars.prototype.onerror = JKL.ParseXML.prototype.onerror;389JKL.ParseXML.LoadVars.prototype.parseResponse = function () {390 var text = this.http.responseText();391 text = text.replace( /\r\n?/g, "\n" ); // new line character392 var hash = {};393 var list = text.split( "&" );394 for( var i=0; i<list.length; i++ ) {395 var eq = list[i].indexOf( "=" );396 if ( eq > -1 ) {397 var key = decodeURIComponent(list[i].substr(0,eq).replace("+","%20"));398 var val = decodeURIComponent(list[i].substr(eq+1).replace("+","%20"));399 hash[key] = val;400 } else {401 hash[list[i]] = "";402 }403 }404 return hash;405};406// ================================================================407// class: JKL.ParseXML.HTTP408// constructer: new JKL.ParseXML.HTTP()409JKL.ParseXML.HTTP = function( url, query, method, textmode ) {410 // debug.print( "new JKL.ParseXML.HTTP( '"+url+"', '"+query+"', '"+method+"', '"+textmode+"' );" );411 this.url = url;412 if ( typeof(query) == "string" ) {413 this.query = query;414 } else {415 this.query = "";416 }417 if ( method ) {418 this.method = method;419 } else if ( typeof(query) == "string" ) {420 this.method = "POST";421 } else {422 this.method = "GET";423 }424 this.textmode = textmode ? true : false;425 this.req = null;426 this.xmldom_flag = false;427 this.onerror_func = null;428 this.callback_func = null;429 this.already_done = null;430 return this;431};432// ================================================================433// class variables434JKL.ParseXML.HTTP.REQUEST_TYPE = "application/x-www-form-urlencoded";435JKL.ParseXML.HTTP.ACTIVEX_XMLDOM = "Microsoft.XMLDOM"; // Msxml2.DOMDocument.5.0436JKL.ParseXML.HTTP.ACTIVEX_XMLHTTP = "Microsoft.XMLHTTP"; // Msxml2.XMLHTTP.3.0437JKL.ParseXML.HTTP.EPOCH_TIMESTAMP = "Thu, 01 Jun 1970 00:00:00 GMT"438// ================================================================439JKL.ParseXML.HTTP.prototype.onerror = JKL.ParseXML.prototype.onerror;440JKL.ParseXML.HTTP.prototype.async = function( func ) {441 this.async_func = func;442}443// ================================================================444// [IE+IXMLDOMElement]445// XML text/xml OK446// XML application/rdf+xml OK447// TEXT text/plain NG448// TEXT others NG449// [IE+IXMLHttpRequest]450// XML text/xml OK451// XML application/rdf+xml NG452// TEXT text/plain OK453// TEXT others OK454// [Firefox+XMLHttpRequest]455// XML text/xml OK456// XML application/rdf+xml OK (overrideMimeType)457// TEXT text/plain OK458// TEXT others OK (overrideMimeType)459// [Opera+XMLHttpRequest]460// XML text/xml OK461// XML application/rdf+xml OK462// TEXT text/plain OK463// TEXT others OK464// ================================================================465JKL.ParseXML.HTTP.prototype.load = function() {466 // create XMLHttpRequest object467 if ( window.ActiveXObject ) { // IE5.5,6,7468 var activex = JKL.ParseXML.HTTP.ACTIVEX_XMLHTTP; // IXMLHttpRequest469 if ( this.method == "GET" && ! this.textmode ) {470 // use IXMLDOMElement to accept any mime types471 // because overrideMimeType() is not available on IE6472 activex = JKL.ParseXML.HTTP.ACTIVEX_XMLDOM; // IXMLDOMElement473 }474 // debug.print( "new ActiveXObject( '"+activex+"' )" );475 this.req = new ActiveXObject( activex );476 } else if ( window.XMLHttpRequest ) { // Firefox, Opera, iCab477 // debug.print( "new XMLHttpRequest()" );478 this.req = new XMLHttpRequest();479 }480 // async mode when call back function is specified481 var async_flag = this.async_func ? true : false;482 // debug.print( "async: "+ async_flag );483 // open for XMLHTTPRequest (not for IXMLDOMElement)484 if ( typeof(this.req.send) != "undefined" ) {485 // debug.print( "open( '"+this.method+"', '"+this.url+"', "+async_flag+" );" );486 this.req.open( this.method, this.url, async_flag );487 }488// // If-Modified-Since: Thu, 01 Jun 1970 00:00:00 GMT489// if ( typeof(this.req.setRequestHeader) != "undefined" ) {490// // debug.print( "If-Modified-Since"+JKL.ParseXML.HTTP.EPOCH_TIMESTAMP );491// this.req.setRequestHeader( "If-Modified-Since", JKL.ParseXML.HTTP.EPOCH_TIMESTAMP );492// }493 // Content-Type: application/x-www-form-urlencoded (request header)494 // Some server does not accept without request content-type.495 if ( typeof(this.req.setRequestHeader) != "undefined" ) {496 // debug.print( "Content-Type: "+JKL.ParseXML.HTTP.REQUEST_TYPE+" (request)" );497 this.req.setRequestHeader( "Content-Type", JKL.ParseXML.HTTP.REQUEST_TYPE );498 }499 // Content-Type: text/xml (response header)500 // FireFox does not accept other mime types like application/rdf+xml etc.501 if ( typeof(this.req.overrideMimeType) != "undefined" && ! this.textmode ) {502 // debug.print( "Content-Type: "+JKL.ParseXML.MIME_TYPE_XML+" (response)" );503 this.req.overrideMimeType( JKL.ParseXML.MIME_TYPE_XML );504 }505 // set call back handler when async mode506 if ( async_flag ) {507 var copy = this;508 copy.already_done = false; // not parsed yet509 var check_func = function () {510 if ( copy.req.readyState != 4 ) return;511 // debug.print( "readyState(async): "+copy.req.readyState );512 var succeed = copy.checkResponse();513 // debug.print( "checkResponse(async): "+succeed );514 if ( ! succeed ) return; // failed515 if ( copy.already_done ) return; // parse only once516 copy.already_done = true; // already parsed517 copy.async_func(); // call back async518 };519 this.req.onreadystatechange = check_func;520 // for document.implementation.createDocument521 // this.req.onload = check_func;522 }523 // send the request and query string524 if ( typeof(this.req.send) != "undefined" ) {525 // debug.print( "XMLHTTPRequest: send( '"+this.query+"' );" );526 this.req.send( this.query ); // XMLHTTPRequest527 } else if ( typeof(this.req.load) != "undefined" ) {528 // debug.print( "IXMLDOMElement: load( '"+this.url+"' );" );529 this.req.async = async_flag;530 this.req.load( this.url ); // IXMLDOMElement531 }532 // just return when async mode533 if ( async_flag ) return;534 var succeed = this.checkResponse();535 // debug.print( "checkResponse(sync): "+succeed );536}537// ================================================================538// method: checkResponse()539JKL.ParseXML.HTTP.prototype.checkResponse = function() {540 // parseError on IXMLDOMElement541 if ( this.req.parseError && this.req.parseError.errorCode != 0 ) {542 // debug.print( "parseError: "+this.req.parseError.reason );543 if ( this.onerror_func ) this.onerror_func( this.req.parseError.reason );544 return false; // failed545 }546 // HTTP response code547 if ( this.req.status-0 > 0 &&548 this.req.status != 200 && // OK549 this.req.status != 206 && // Partial Content550 this.req.status != 304 ) { // Not Modified551 // debug.print( "status: "+this.req.status );552 if ( this.onerror_func ) this.onerror_func( this.req.status );553 return false; // failed554 }555 return true; // succeed556}557// ================================================================558// method: documentElement()559// return: XML DOM in response body560JKL.ParseXML.HTTP.prototype.documentElement = function() {561 // debug.print( "documentElement: "+this.req );562 if ( ! this.req ) return;563 if ( this.req.responseXML ) {564 return this.req.responseXML.documentElement; // XMLHTTPRequest565 } else {566 return this.req.documentElement; // IXMLDOMDocument567 }568}569// ================================================================570// method: responseText()571// return: text string in response body572JKL.ParseXML.HTTP.prototype.responseText = function() {573 // debug.print( "responseText: "+this.req );574 if ( ! this.req ) return;575 // Safari and Konqueror cannot understand the encoding of text files.576 if ( navigator.appVersion.match( "KHTML" ) ) {577 var esc = escape( this.req.responseText );578// debug.print( "escape: "+esc );579 if ( ! esc.match("%u") && esc.match("%") ) {580 return decodeURIComponent(esc);581 }582 }583 return this.req.responseText;584}585// ================================================================586// http://msdn.microsoft.com/library/en-us/xmlsdk/html/d051f7c5-e882-42e8-a5b6-d1ce67af275c.asp...
parsexml.js
Source: parsexml.js
1// ================================================================2// jkl-parsexml.js ---- JavaScript Kantan Library for Parsing XML3// Copyright 2005-2007 Kawasaki Yusuke <u-suke@kawa.net>4// http://www.kawa.net/works/js/jkl/parsexml.html5// ================================================================6// v0.01 2005/05/18 first release7// v0.02 2005/05/20 Opera 8.0beta may be abailable but somtimes crashed8// v0.03 2005/05/20 overrideMimeType( "text/xml" );9// v0.04 2005/05/21 class variables: REQUEST_TYPE, RESPONSE_TYPE10// v0.05 2005/05/22 use Msxml2.DOMDocument.5.0 for GET method on IE611// v0.06 2005/05/22 CDATA_SECTION_NODE12// v0.07 2005/05/23 use Microsoft.XMLDOM for GET method on IE613// v0.10 2005/10/11 new function: JKL.ParseXML.HTTP.responseText()14// v0.11 2005/10/13 new sub class: JKL.ParseXML.Text, JSON and DOM.15// v0.12 2005/10/14 new sub class: JKL.ParseXML.CSV and CSVmap.16// v0.13 2005/10/28 bug fixed: TEXT_NODE regexp for white spaces17// v0.14 2005/11/06 bug fixed: TEXT_NODE regexp at Safari18// v0.15 2005/11/08 bug fixed: JKL.ParseXML.CSV.async() method19// v0.16 2005/11/15 new sub class: LoadVars, and UTF-8 text on Safari20// v0.18 2005/11/16 improve: UTF-8 text file on Safari21// v0.19 2006/02/03 use XMLHTTPRequest instead of ActiveX on IE7,iCab22// v0.20 2006/03/22 (skipped)23// v0.21 2006/11/30 use ActiveX again on IE724// v0.22 2007/01/04 JKL.ParseXML.JSON.parseResponse() updated25// ================================================================26if ( typeof(JKL) == 'undefined' ) JKL = function() {};27// ================================================================28// class: JKL.ParseXML 29JKL.ParseXML = function ( url, query, method ) {30 // debug.print( "new JKL.ParseXML( '"+url+"', '"+query+"', '"+method+"' );" );31 this.http = new JKL.ParseXML.HTTP( url, query, method, false );32 return this;33};34// ================================================================35// class variables36JKL.ParseXML.VERSION = "0.22";37JKL.ParseXML.MIME_TYPE_XML = "text/xml";38JKL.ParseXML.MAP_NODETYPE = [39 "",40 "ELEMENT_NODE", // 141 "ATTRIBUTE_NODE", // 242 "TEXT_NODE", // 343 "CDATA_SECTION_NODE", // 444 "ENTITY_REFERENCE_NODE", // 545 "ENTITY_NODE", // 646 "PROCESSING_INSTRUCTION_NODE", // 747 "COMMENT_NODE", // 848 "DOCUMENT_NODE", // 949 "DOCUMENT_TYPE_NODE", // 1050 "DOCUMENT_FRAGMENT_NODE", // 1151 "NOTATION_NODE" // 1252];53// ================================================================54// define callback function (ajax)55JKL.ParseXML.prototype.async = function ( func, args ) {56 this.callback_func = func; // callback function57 this.callback_arg = args; // first argument58};59JKL.ParseXML.prototype.onerror = function ( func, args ) {60 this.onerror_func = func; // callback function61};62// ================================================================63// method: parse()64// return: parsed object65// Download a file from remote server and parse it.66JKL.ParseXML.prototype.parse = function () {67 if ( ! this.http ) return;68 // set onerror call back 69 if ( this.onerror_func ) {70 this.http.onerror( this.onerror_func );71 }72 if ( this.callback_func ) { // async mode73 var copy = this;74 var proc = function() {75 if ( ! copy.http ) return;76 var data = copy.parseResponse();77 copy.callback_func( data, copy.callback_arg ); // call back78 };79 this.http.async( proc );80 }81 this.http.load();82 if ( ! this.callback_func ) { // sync mode83 var data = this.parseResponse();84 return data;85 }86};87// ================================================================88// every child/children into array89JKL.ParseXML.prototype.setOutputArrayAll = function () {90 this.setOutputArray( true );91}92// a child into scalar, children into array93JKL.ParseXML.prototype.setOutputArrayAuto = function () {94 this.setOutputArray( null );95}96// every child/children into scalar (first sibiling only)97JKL.ParseXML.prototype.setOutputArrayNever = function () {98 this.setOutputArray( false );99}100// specified child/children into array, other child/children into scalar101JKL.ParseXML.prototype.setOutputArrayElements = function ( list ) {102 this.setOutputArray( list );103}104// specify how to treate child/children into scalar/array105JKL.ParseXML.prototype.setOutputArray = function ( mode ) {106 if ( typeof(mode) == "string" ) {107 mode = [ mode ]; // string into array108 }109 if ( mode && typeof(mode) == "object" ) {110 if ( mode.length < 0 ) {111 mode = false; // false when array == [] 112 } else {113 var hash = {};114 for( var i=0; i<mode.length; i++ ) {115 hash[mode[i]] = true;116 }117 mode = hash; // array into hashed array118 if ( mode["*"] ) {119 mode = true; // true when includes "*"120 }121 } 122 } 123 this.usearray = mode;124}125// ================================================================126// method: parseResponse()127JKL.ParseXML.prototype.parseResponse = function () {128 var root = this.http.documentElement();129 var data = this.parseDocument( root );130 return data;131}132// ================================================================133// convert from DOM root node to JavaScript Object 134// method: parseElement( rootElement )135JKL.ParseXML.prototype.parseDocument = function ( root ) {136 // debug.print( "parseDocument: "+root );137 if ( ! root ) return;138 var ret = this.parseElement( root ); // parse root node139 // debug.print( "parsed: "+ret );140 if ( this.usearray == true ) { // always into array141 ret = [ ret ];142 } else if ( this.usearray == false ) { // always into scalar143 //144 } else if ( this.usearray == null ) { // automatic145 //146 } else if ( this.usearray[root.nodeName] ) { // specified tag147 ret = [ ret ];148 }149 var json = {};150 json[root.nodeName] = ret; // root nodeName151 return json;152};153// ================================================================154// convert from DOM Element to JavaScript Object 155// method: parseElement( element )156JKL.ParseXML.prototype.parseElement = function ( elem ) {157 // debug.print( "nodeType: "+JKL.ParseXML.MAP_NODETYPE[elem.nodeType]+" <"+elem.nodeName+">" );158 // COMMENT_NODE159 if ( elem.nodeType == 7 ) {160 return;161 }162 // TEXT_NODE CDATA_SECTION_NODE163 if ( elem.nodeType == 3 || elem.nodeType == 4 ) {164 // var bool = elem.nodeValue.match( /[^\u0000-\u0020]/ );165 var bool = elem.nodeValue.match( /[^\x00-\x20]/ ); // for Safari166 if ( bool == null ) return; // ignore white spaces167 // debug.print( "TEXT_NODE: "+elem.nodeValue.length+ " "+bool );168 return elem.nodeValue;169 }170 var retval;171 var cnt = {};172 // parse attributes173 if ( elem.attributes && elem.attributes.length ) {174 retval = {};175 for ( var i=0; i<elem.attributes.length; i++ ) {176 var key = elem.attributes[i].nodeName;177 if ( typeof(key) != "string" ) continue;178 var val = elem.attributes[i].nodeValue;179 if ( ! val ) continue;180 if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;181 cnt[key] ++;182 this.addNode( retval, key, cnt[key], val );183 }184 }185 // parse child nodes (recursive)186 if ( elem.childNodes && elem.childNodes.length ) {187 var textonly = true;188 if ( retval ) textonly = false; // some attributes exists189 for ( var i=0; i<elem.childNodes.length && textonly; i++ ) {190 var ntype = elem.childNodes[i].nodeType;191 if ( ntype == 3 || ntype == 4 ) continue;192 textonly = false;193 }194 if ( textonly ) {195 if ( ! retval ) retval = "";196 for ( var i=0; i<elem.childNodes.length; i++ ) {197 retval += elem.childNodes[i].nodeValue;198 }199 } else {200 if ( ! retval ) retval = {};201 for ( var i=0; i<elem.childNodes.length; i++ ) {202 var key = elem.childNodes[i].nodeName;203 if ( typeof(key) != "string" ) continue;204 var val = this.parseElement( elem.childNodes[i] );205 if ( ! val ) continue;206 if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;207 cnt[key] ++;208 this.addNode( retval, key, cnt[key], val );209 }210 }211 }212 return retval;213};214// ================================================================215// method: addNode( hash, key, count, value )216JKL.ParseXML.prototype.addNode = function ( hash, key, cnts, val ) {217 if ( this.usearray == true ) { // into array218 if ( cnts == 1 ) hash[key] = [];219 hash[key][hash[key].length] = val; // push220 } else if ( this.usearray == false ) { // into scalar221 if ( cnts == 1 ) hash[key] = val; // only 1st sibling222 } else if ( this.usearray == null ) {223 if ( cnts == 1 ) { // 1st sibling224 hash[key] = val;225 } else if ( cnts == 2 ) { // 2nd sibling226 hash[key] = [ hash[key], val ];227 } else { // 3rd sibling and more228 hash[key][hash[key].length] = val;229 }230 } else if ( this.usearray[key] ) {231 if ( cnts == 1 ) hash[key] = [];232 hash[key][hash[key].length] = val; // push233 } else {234 if ( cnts == 1 ) hash[key] = val; // only 1st sibling235 }236};237// ================================================================238// class: JKL.ParseXML.Text 239JKL.ParseXML.Text = function ( url, query, method ) {240 // debug.print( "new JKL.ParseXML.Text( '"+url+"', '"+query+"', '"+method+"' );" );241 this.http = new JKL.ParseXML.HTTP( url, query, method, true );242 return this;243};244JKL.ParseXML.Text.prototype.parse = JKL.ParseXML.prototype.parse;245JKL.ParseXML.Text.prototype.async = JKL.ParseXML.prototype.async;246JKL.ParseXML.Text.prototype.onerror = JKL.ParseXML.prototype.onerror;247JKL.ParseXML.Text.prototype.parseResponse = function () {248 var data = this.http.responseText();249 return data;250}251// ================================================================252// class: JKL.ParseXML.JSON253JKL.ParseXML.JSON = function ( url, query, method ) {254 // debug.print( "new JKL.ParseXML.JSON( '"+url+"', '"+query+"', '"+method+"' );" );255 this.http = new JKL.ParseXML.HTTP( url, query, method, true );256 return this;257};258JKL.ParseXML.JSON.prototype.parse = JKL.ParseXML.prototype.parse;259JKL.ParseXML.JSON.prototype.async = JKL.ParseXML.prototype.async;260JKL.ParseXML.JSON.prototype.onerror = JKL.ParseXML.prototype.onerror;261JKL.ParseXML.JSON.prototype.parseResponse = function () {262 var text = this.http.responseText();263 // http://www.antimon2.atnifty.com/2007/01/jklparsexmljson.html264 if ( typeof(text) == 'undefined' ) return;265 if ( ! text.length ) return;266 var data = eval( "("+text+")" );267 return data;268}269// ================================================================270// class: JKL.ParseXML.DOM271JKL.ParseXML.DOM = function ( url, query, method ) {272 // debug.print( "new JKL.ParseXML.DOM( '"+url+"', '"+query+"', '"+method+"' );" );273 this.http = new JKL.ParseXML.HTTP( url, query, method, false );274 return this;275};276JKL.ParseXML.DOM.prototype.parse = JKL.ParseXML.prototype.parse;277JKL.ParseXML.DOM.prototype.async = JKL.ParseXML.prototype.async;278JKL.ParseXML.DOM.prototype.onerror = JKL.ParseXML.prototype.onerror;279JKL.ParseXML.DOM.prototype.parseResponse = function () {280 var data = this.http.documentElement();281 return data;282}283// ================================================================284// class: JKL.ParseXML.CSV285JKL.ParseXML.CSV = function ( url, query, method ) {286 // debug.print( "new JKL.ParseXML.CSV( '"+url+"', '"+query+"', '"+method+"' );" );287 this.http = new JKL.ParseXML.HTTP( url, query, method, true );288 return this;289};290JKL.ParseXML.CSV.prototype.parse = JKL.ParseXML.prototype.parse;291JKL.ParseXML.CSV.prototype.async = JKL.ParseXML.prototype.async;292JKL.ParseXML.CSV.prototype.onerror = JKL.ParseXML.prototype.onerror;293JKL.ParseXML.CSV.prototype.parseResponse = function () {294 var text = this.http.responseText();295 var data = this.parseCSV( text );296 return data;297}298JKL.ParseXML.CSV.prototype.parseCSV = function ( text ) {299 text = text.replace( /\r\n?/g, "\n" ); // new line character300 var pos = 0;301 var len = text.length;302 var table = [];303 while( pos<len ) {304 var line = [];305 while( pos<len ) {306 if ( text.charAt(pos) == '"' ) { // "..." quoted column307 var nextquote = text.indexOf( '"', pos+1 );308 while ( nextquote<len && nextquote > -1 ) {309 if ( text.charAt(nextquote+1) != '"' ) {310 break; // end of column311 }312 nextquote = text.indexOf( '"', nextquote+2 );313 }314 if ( nextquote < 0 ) {315 // unclosed quote316 } else if ( text.charAt(nextquote+1) == "," ) { // end of column317 var quoted = text.substr( pos+1, nextquote-pos-1 );318 quoted = quoted.replace(/""/g,'"');319 line[line.length] = quoted;320 pos = nextquote+2;321 continue;322 } else if ( text.charAt(nextquote+1) == "\n" || // end of line323 len==nextquote+1 ) { // end of file324 var quoted = text.substr( pos+1, nextquote-pos-1 );325 quoted = quoted.replace(/""/g,'"');326 line[line.length] = quoted;327 pos = nextquote+2;328 break;329 } else {330 // invalid column331 }332 }333 var nextcomma = text.indexOf( ",", pos );334 var nextnline = text.indexOf( "\n", pos );335 if ( nextnline < 0 ) nextnline = len;336 if ( nextcomma > -1 && nextcomma < nextnline ) {337 line[line.length] = text.substr( pos, nextcomma-pos );338 pos = nextcomma+1;339 } else { // end of line340 line[line.length] = text.substr( pos, nextnline-pos );341 pos = nextnline+1;342 break;343 }344 }345 if ( line.length >= 0 ) {346 table[table.length] = line; // push line347 }348 }349 if ( table.length < 0 ) return; // null data350 return table;351};352// ================================================================353// class: JKL.ParseXML.CSVmap354JKL.ParseXML.CSVmap = function ( url, query, method ) {355 // debug.print( "new JKL.ParseXML.CSVmap( '"+url+"', '"+query+"', '"+method+"' );" );356 this.http = new JKL.ParseXML.HTTP( url, query, method, true );357 return this;358};359JKL.ParseXML.CSVmap.prototype.parse = JKL.ParseXML.prototype.parse;360JKL.ParseXML.CSVmap.prototype.async = JKL.ParseXML.prototype.async;361JKL.ParseXML.CSVmap.prototype.onerror = JKL.ParseXML.prototype.onerror;362JKL.ParseXML.CSVmap.prototype.parseCSV = JKL.ParseXML.CSV.prototype.parseCSV;363JKL.ParseXML.CSVmap.prototype.parseResponse = function () {364 var text = this.http.responseText();365 var source = this.parseCSV( text );366 if ( ! source ) return;367 if ( source.length < 0 ) return;368 var title = source.shift(); // first line as title369 var data = [];370 for( var i=0; i<source.length; i++ ) {371 var hash = {};372 for( var j=0; j<title.length && j<source[i].length; j++ ) {373 hash[title[j]] = source[i][j]; // array to map374 }375 data[data.length] = hash; // push line376 }377 return data;378}379// ================================================================380// class: JKL.ParseXML.LoadVars381JKL.ParseXML.LoadVars = function ( url, query, method ) {382 // debug.print( "new JKL.ParseXML.LoadVars( '"+url+"', '"+query+"', '"+method+"' );" );383 this.http = new JKL.ParseXML.HTTP( url, query, method, true );384 return this;385};386JKL.ParseXML.LoadVars.prototype.parse = JKL.ParseXML.prototype.parse;387JKL.ParseXML.LoadVars.prototype.async = JKL.ParseXML.prototype.async;388JKL.ParseXML.LoadVars.prototype.onerror = JKL.ParseXML.prototype.onerror;389JKL.ParseXML.LoadVars.prototype.parseResponse = function () {390 var text = this.http.responseText();391 text = text.replace( /\r\n?/g, "\n" ); // new line character392 var hash = {};393 var list = text.split( "&" );394 for( var i=0; i<list.length; i++ ) {395 var eq = list[i].indexOf( "=" );396 if ( eq > -1 ) {397 var key = decodeURIComponent(list[i].substr(0,eq).replace("+","%20"));398 var val = decodeURIComponent(list[i].substr(eq+1).replace("+","%20"));399 hash[key] = val;400 } else {401 hash[list[i]] = "";402 }403 }404 return hash;405};406// ================================================================407// class: JKL.ParseXML.HTTP408// constructer: new JKL.ParseXML.HTTP()409JKL.ParseXML.HTTP = function( url, query, method, textmode ) {410 // debug.print( "new JKL.ParseXML.HTTP( '"+url+"', '"+query+"', '"+method+"', '"+textmode+"' );" );411 this.url = url;412 if ( typeof(query) == "string" ) {413 this.query = query;414 } else {415 this.query = "";416 }417 if ( method ) {418 this.method = method;419 } else if ( typeof(query) == "string" ) {420 this.method = "POST";421 } else {422 this.method = "GET";423 }424 this.textmode = textmode ? true : false;425 this.req = null;426 this.xmldom_flag = false;427 this.onerror_func = null;428 this.callback_func = null;429 this.already_done = null;430 return this;431};432// ================================================================433// class variables434JKL.ParseXML.HTTP.REQUEST_TYPE = "application/x-www-form-urlencoded";435JKL.ParseXML.HTTP.ACTIVEX_XMLDOM = "Microsoft.XMLDOM"; // Msxml2.DOMDocument.5.0436JKL.ParseXML.HTTP.ACTIVEX_XMLHTTP = "Microsoft.XMLHTTP"; // Msxml2.XMLHTTP.3.0437JKL.ParseXML.HTTP.EPOCH_TIMESTAMP = "Thu, 01 Jun 1970 00:00:00 GMT"438// ================================================================439JKL.ParseXML.HTTP.prototype.onerror = JKL.ParseXML.prototype.onerror;440JKL.ParseXML.HTTP.prototype.async = function( func ) {441 this.async_func = func;442}443// ================================================================444// [IE+IXMLDOMElement]445// XML text/xml OK446// XML application/rdf+xml OK447// TEXT text/plain NG448// TEXT others NG449// [IE+IXMLHttpRequest]450// XML text/xml OK451// XML application/rdf+xml NG452// TEXT text/plain OK453// TEXT others OK454// [Firefox+XMLHttpRequest]455// XML text/xml OK456// XML application/rdf+xml OK (overrideMimeType)457// TEXT text/plain OK458// TEXT others OK (overrideMimeType)459// [Opera+XMLHttpRequest]460// XML text/xml OK461// XML application/rdf+xml OK462// TEXT text/plain OK463// TEXT others OK464// ================================================================465JKL.ParseXML.HTTP.prototype.load = function() {466 // create XMLHttpRequest object467 if ( window.ActiveXObject ) { // IE5.5,6,7468 var activex = JKL.ParseXML.HTTP.ACTIVEX_XMLHTTP; // IXMLHttpRequest469 if ( this.method == "GET" && ! this.textmode ) {470 // use IXMLDOMElement to accept any mime types471 // because overrideMimeType() is not available on IE6472 activex = JKL.ParseXML.HTTP.ACTIVEX_XMLDOM; // IXMLDOMElement473 }474 // debug.print( "new ActiveXObject( '"+activex+"' )" );475 this.req = new ActiveXObject( activex );476 } else if ( window.XMLHttpRequest ) { // Firefox, Opera, iCab477 // debug.print( "new XMLHttpRequest()" );478 this.req = new XMLHttpRequest();479 }480 // async mode when call back function is specified481 var async_flag = this.async_func ? true : false;482 // debug.print( "async: "+ async_flag );483 // open for XMLHTTPRequest (not for IXMLDOMElement)484 if ( typeof(this.req.send) != "undefined" ) {485 // debug.print( "open( '"+this.method+"', '"+this.url+"', "+async_flag+" );" );486 this.req.open( this.method, this.url, async_flag );487 }488// // If-Modified-Since: Thu, 01 Jun 1970 00:00:00 GMT489// if ( typeof(this.req.setRequestHeader) != "undefined" ) {490// // debug.print( "If-Modified-Since"+JKL.ParseXML.HTTP.EPOCH_TIMESTAMP );491// this.req.setRequestHeader( "If-Modified-Since", JKL.ParseXML.HTTP.EPOCH_TIMESTAMP );492// }493 // Content-Type: application/x-www-form-urlencoded (request header)494 // Some server does not accept without request content-type.495 if ( typeof(this.req.setRequestHeader) != "undefined" ) {496 // debug.print( "Content-Type: "+JKL.ParseXML.HTTP.REQUEST_TYPE+" (request)" );497 this.req.setRequestHeader( "Content-Type", JKL.ParseXML.HTTP.REQUEST_TYPE );498 }499 // Content-Type: text/xml (response header)500 // FireFox does not accept other mime types like application/rdf+xml etc.501 if ( typeof(this.req.overrideMimeType) != "undefined" && ! this.textmode ) {502 // debug.print( "Content-Type: "+JKL.ParseXML.MIME_TYPE_XML+" (response)" );503 this.req.overrideMimeType( JKL.ParseXML.MIME_TYPE_XML );504 }505 // set call back handler when async mode506 if ( async_flag ) {507 var copy = this;508 copy.already_done = false; // not parsed yet509 var check_func = function () {510 if ( copy.req.readyState != 4 ) return;511 // debug.print( "readyState(async): "+copy.req.readyState );512 var succeed = copy.checkResponse();513 // debug.print( "checkResponse(async): "+succeed );514 if ( ! succeed ) return; // failed515 if ( copy.already_done ) return; // parse only once516 copy.already_done = true; // already parsed517 copy.async_func(); // call back async518 };519 this.req.onreadystatechange = check_func;520 // for document.implementation.createDocument521 // this.req.onload = check_func;522 }523 // send the request and query string524 if ( typeof(this.req.send) != "undefined" ) {525 // debug.print( "XMLHTTPRequest: send( '"+this.query+"' );" );526 this.req.send( this.query ); // XMLHTTPRequest527 } else if ( typeof(this.req.load) != "undefined" ) {528 // debug.print( "IXMLDOMElement: load( '"+this.url+"' );" );529 this.req.async = async_flag;530 this.req.load( this.url ); // IXMLDOMElement531 }532 // just return when async mode533 if ( async_flag ) return;534 var succeed = this.checkResponse();535 // debug.print( "checkResponse(sync): "+succeed );536}537// ================================================================538// method: checkResponse()539JKL.ParseXML.HTTP.prototype.checkResponse = function() {540 // parseError on IXMLDOMElement541 if ( this.req.parseError && this.req.parseError.errorCode != 0 ) {542 // debug.print( "parseError: "+this.req.parseError.reason );543 if ( this.onerror_func ) this.onerror_func( this.req.parseError.reason );544 return false; // failed545 }546 // HTTP response code547 if ( this.req.status-0 > 0 &&548 this.req.status != 200 && // OK549 this.req.status != 206 && // Partial Content550 this.req.status != 304 ) { // Not Modified551 // debug.print( "status: "+this.req.status );552 if ( this.onerror_func ) this.onerror_func( this.req.status );553 return false; // failed554 }555 return true; // succeed556}557// ================================================================558// method: documentElement()559// return: XML DOM in response body560JKL.ParseXML.HTTP.prototype.documentElement = function() {561 // debug.print( "documentElement: "+this.req );562 if ( ! this.req ) return;563 if ( this.req.responseXML ) {564 return this.req.responseXML.documentElement; // XMLHTTPRequest565 } else {566 return this.req.documentElement; // IXMLDOMDocument567 }568}569// ================================================================570// method: responseText()571// return: text string in response body572JKL.ParseXML.HTTP.prototype.responseText = function() {573 // debug.print( "responseText: "+this.req );574 if ( ! this.req ) return;575 // Safari and Konqueror cannot understand the encoding of text files.576 if ( navigator.appVersion.match( "KHTML" ) ) {577 var esc = escape( this.req.responseText );578// debug.print( "escape: "+esc );579 if ( ! esc.match("%u") && esc.match("%") ) {580 return decodeURIComponent(esc);581 }582 }583 return this.req.responseText;584}585// ================================================================586// http://msdn.microsoft.com/library/en-us/xmlsdk/html/d051f7c5-e882-42e8-a5b6-d1ce67af275c.asp...
erGetItems.js
Source: erGetItems.js
...79 execute: function _execute()80 {81 //exchWebService.commonFunctions.LOG("erGetTaskItemsRequest.execute\n");82 var root = xml2json.newJSON();83 xml2json.parseXML(root, '<nsMessages:GetItem xmlns:nsMessages="'+nsMessagesStr+'" xmlns:nsTypes="'+nsTypesStr+'"/>');84 var req = root[telements][0];85 var itemShape = xml2json.addTag(req, "ItemShape", "nsMessages", null);86 xml2json.addTag(itemShape, "BaseShape", "nsTypes", "IdOnly"); 87// xml2json.addTag(itemShape, "BodyType", "nsTypes", "Text");88 xml2json.addTag(itemShape, "BodyType", "nsTypes", "Best");89 var additionalProperties = xml2json.addTag(itemShape, "AdditionalProperties", "nsTypes", null);90 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:ItemId'/>");91 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:ParentFolderId'/>");92 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:ItemClass'/>");93 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:Attachments'/>");94 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:Subject'/>");95 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:DateTimeReceived'/>");96 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:Size'/>");97 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:Categories'/>");98 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:HasAttachments'/>");99 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:Importance'/>");100 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:IsDraft'/>");101 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:IsFromMe'/>");102 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:IsResend'/>");103 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:IsSubmitted'/>");104 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:IsUnmodified'/>");105 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:DateTimeSent'/>");106 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:DateTimeCreated'/>");107 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:Body'/>");108 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:ResponseObjects'/>");109 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:Sensitivity'/>");110 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:ReminderDueBy'/>");111 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:ReminderIsSet'/>");112 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:ReminderMinutesBeforeStart'/>");113 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:EffectiveRights'/>");114 //xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:MimeContent'/>");115 this.exchangeStatistics = Cc["@1st-setup.nl/exchange/statistics;1"]116 .getService(Ci.mivExchangeStatistics);117 if ((this.exchangeStatistics.getServerVersion(this.serverUrl).indexOf("Exchange2010") > -1) || (this.exchangeStatistics.getServerVersion(this.serverUrl).indexOf("Exchange2013") > -1 )) {118 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='item:UniqueBody'/>");119 }120 else { // Exchange2007121 }122 var extFieldURI;123 extFieldURI = xml2json.addTag(additionalProperties, "ExtendedFieldURI", "nsTypes", null);124 xml2json.setAttribute(extFieldURI, "DistinguishedPropertySetId", "Common");125 xml2json.setAttribute(extFieldURI, "PropertyId", MAPI_PidLidReminderSignalTime);126 xml2json.setAttribute(extFieldURI, "PropertyType", "SystemTime");127 extFieldURI = xml2json.addTag(additionalProperties, "ExtendedFieldURI", "nsTypes", null);128 xml2json.setAttribute(extFieldURI, "DistinguishedPropertySetId", "Common");129 xml2json.setAttribute(extFieldURI, "PropertyId", MAPI_PidLidReminderSet);130 xml2json.setAttribute(extFieldURI, "PropertyType", "Boolean");131 132 extFieldURI = xml2json.addTag(additionalProperties, "ExtendedFieldURI", "nsTypes", null);133 xml2json.setAttribute(extFieldURI, "DistinguishedPropertySetId", "Common");134 xml2json.setAttribute(extFieldURI, "PropertyId", MAPI_PidLidReminderDelta);135 xml2json.setAttribute(extFieldURI, "PropertyType", "Integer");136 // Calendar fields137 switch (this.folderClass) {138 case "IPF.Appointment":139 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:Start'/>");140 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:End'/>");141 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:OriginalStart'/>");142 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:IsAllDayEvent'/>");143 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:LegacyFreeBusyStatus'/>");144 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:Location'/>");145 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:When'/>");146 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:IsMeeting'/>");147 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:IsCancelled'/>");148 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:IsRecurring'/>");149 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:MeetingRequestWasSent'/>");150 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:IsResponseRequested'/>");151 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:CalendarItemType'/>");152 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:MyResponseType'/>");153 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:Organizer'/>");154 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:RequiredAttendees'/>");155 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:OptionalAttendees'/>");156 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:Resources'/>");157 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:Duration'/>");158 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:TimeZone'/>");159 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:Recurrence'/>");160 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:ConferenceType'/>");161 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:AllowNewTimeProposal'/>");162 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:IsOnlineMeeting'/>");163 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:MeetingWorkspaceUrl'/>");164 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:UID'/>");165 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:RecurrenceId'/>");166 if ((this.exchangeStatistics.getServerVersion(this.serverUrl).indexOf("Exchange2010") > -1) || (this.exchangeStatistics.getServerVersion(this.serverUrl).indexOf("Exchange2013") > -1 )) {167 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:StartTimeZone'/>");168 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:EndTimeZone'/>");169 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:ModifiedOccurrences'/>");170 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:DeletedOccurrences'/>");171 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:FirstOccurrence'/>");172 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:LastOccurrence'/>");173 }174 else { // Exchange2007175 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='calendar:MeetingTimeZone'/>");176 }177 break; 178 case "IPF.Task":179 //Task fields180 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:ActualWork'/>");181 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:AssignedTime'/>");182 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:BillingInformation'/>");183 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:ChangeCount'/>");184 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:Companies'/>");185 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:CompleteDate'/>");186 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:Contacts'/>");187 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:DelegationState'/>");188 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:Delegator'/>");189 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:DueDate'/>");190 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:IsAssignmentEditable'/>");191 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:IsComplete'/>");192 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:IsRecurring'/>");193 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:IsTeamTask'/>");194 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:Mileage'/>");195 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:Owner'/>");196 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:PercentComplete'/>");197 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:Recurrence'/>");198 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:StartDate'/>");199 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:Status'/>");200 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:StatusDescription'/>");201 xml2json.parseXML(additionalProperties,"<nsTypes:FieldURI FieldURI='task:TotalWork'/>");202 extFieldURI = xml2json.addTag(additionalProperties, "ExtendedFieldURI", "nsTypes", null);203 xml2json.setAttribute(extFieldURI, "DistinguishedPropertySetId", "Task");204 xml2json.setAttribute(extFieldURI, "PropertyId", MAPI_PidLidTaskAccepted);205 xml2json.setAttribute(extFieldURI, "PropertyType", "Boolean");206 extFieldURI = xml2json.addTag(additionalProperties, "ExtendedFieldURI", "nsTypes", null);207 xml2json.setAttribute(extFieldURI, "DistinguishedPropertySetId", "Task");208 xml2json.setAttribute(extFieldURI, "PropertyId", MAPI_PidLidTaskLastUpdate);209 xml2json.setAttribute(extFieldURI, "PropertyType", "SystemTime");210 extFieldURI = xml2json.addTag(additionalProperties, "ExtendedFieldURI", "nsTypes", null);211 xml2json.setAttribute(extFieldURI, "DistinguishedPropertySetId", "Task");212 xml2json.setAttribute(extFieldURI, "PropertyId", MAPI_PidLidTaskAcceptanceState);213 xml2json.setAttribute(extFieldURI, "PropertyType", "Integer");214 extFieldURI = xml2json.addTag(additionalProperties, "ExtendedFieldURI", "nsTypes", null);215 xml2json.setAttribute(extFieldURI, "DistinguishedPropertySetId", "Task");...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const userAgent = await page.evaluate(() => navigator.userAgent);7 console.log(userAgent);8 const xml = await page.evaluate(() => document.body.innerHTML);9 const { parse } = require('playwright/lib/server/parseXML');10 const parsed = parse(xml);11 console.log(parsed);12 await browser.close();13})();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const xml = await page.evaluate(() => {7 const parser = new DOMParser();8 const xml = parser.parseFromString('<xml></xml>', 'text/xml');9 return xml;10 });11 console.log(xml);12 await browser.close();13})();14- [Playwright Github](
Using AI Code Generation
1const { parseXML } = require('@playwright/test/lib/utils/xml');2</bookstore>`;3const result = parseXML(xml);4console.log(result);5console.log(result.bookstore.book[0].title._text);6console.log(result.bookstore.book[0].title._attrs.lang);7console.log(result.bookstore.book[1].price._text);
Using AI Code Generation
1const { parseXML } = require('@playwright/test/lib/utils/xml');2const xml = '<root><a>1</a><b>2</b></root>';3const parsedXML = parseXML(xml);4console.log(parsedXML);5const { test } = require('@playwright/test');6const { parseXML } = test;7const xml = '<root><a>1</a><b>2</b></root>';8const parsedXML = parseXML(xml);9console.log(parsedXML);10const { parseXML } = require('playwright');11const xml = '<root><a>1</a><b>2</b></root>';12const parsedXML = parseXML(xml);13console.log(parsedXML);14 1 passed (1s)
Using AI Code Generation
1const { parseXML } = require('@playwright/test/lib/utils/xml');2`;3const result = parseXML(xml);4console.log(result);5const { JUnitReporter } = require('@playwright/test/lib/reporters/junit');6const { parseXML } = require('@playwright/test/lib/utils/xml');7`;8const result = parseXML(xml);9const reporter = new JUnitReporter();10reporter.onBegin();11reporter.onTestBegin({ title: 'test', fullName: 'test' });12reporter.onTestEnd({ title: 'test', fullName: 'test', duration: 0 });13reporter.onEnd();14const report = reporter.report();15We welcome contributions to Playwright Test. Please read [CONTRIBUTING.md](
Using AI Code Generation
1const { parseXML } = require('playwright/lib/utils/xml');2</root>`;3const doc = await parseXML(xml);4console.log(doc.documentElement.outerHTML);5### `parseXML(xml)`6[Apache-2.0](LICENSE)
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!