public
Last active

Extends jsdb XML object. Adds toObject (Straightforward translation to key/value pairs.)

  • Download Gist
xml_utils.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
load('xml.js');
 
// XML.js type to native object.
// Straightforward translation. Notes:
// 1. If a node has children or attributes *and* CDATA, the CDATA will be put in a field named '#cdata'
// 2. Order is not necessarily preserved.
// 3. If a node has multiple children with the same name, they are placed into an array.
XML.prototype.toObject=function( obj )
{
var has_children = this.children.length;
var has_params = this.params.count;
var has_cdata = this.cdata.length;
var is_object = has_children || has_params;
var is_field = (!is_object) && has_cdata;
var x;
 
if ( is_object ) {
var out = new Object;
 
// 3. If a node has multiple children with the same name, they are placed into an array.
if ( obj[ this.name ] ) {
if ( obj[ this.name ] instanceof Array ) {
obj[ this.name ].push ( out );
}
else {
var first_result = obj[ this.name ];
obj[ this.name ] = [ first_result, out ]
}
} else {
obj[ this.name ] = out;
}
 
for(x=0; x<this.params.count; x++) {
out[ this.params.name(x) ] = this.params.value(x);
}
 
for(x in this.children) {
this.children[x].toObject(out);
}
 
// 1. If a node has children or attributes *and* CDATA, the CDATA will be put in a field named '#cdata'
if (has_cdata) {
obj[ '#cdata' ] = this.cdata;
}
} else if ( is_field ) {
// 3. If a node has multiple children with the same name, they are placed into an array.
if ( obj[ this.name ] ) {
if ( obj[ this.name ] instanceof Array ) {
obj[ this.name ].push ( this.cdata );
} else {
var first_result = obj[ this.name ];
obj[ this.name ] = [ first_result, this.cdata ]
}
} else {
obj[ this.name ] = this.cdata;
}
}
}
 
XML.readObject=function( text ) {
var out_xml = XML.read( text );
var out_obj = new Object;
 
out_xml.toObject( out_obj );
return (out_obj);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.