JavaScript code for converting xml to json. For more information, see
The Code is as follows:
Function xmlToJson (xml ){
// Create the return object
Var obj = {};
If (xml. nodeType = 1) {// element
// Do attributes
If (xml. attributes. length> 0 ){
Obj ["@ attributes"] = {};
For (var j = 0; j <xml. attributes. length; j ++ ){
Var attribute = xml. attributes. item (j );
Obj ["@ attributes"] [attribute. nodeName] = attribute. nodeValue;
}
}
} Else if (xml. nodeType = 3) {// text
Obj = xml. nodeValue;
}
// Do children
If (xml. hasChildNodes ()){
For (var I = 0; I <xml. childNodes. length; I ++ ){
Var item = xml. childNodes. item (I );
Var nodeName = item. nodeName;
If (typeof (obj [nodeName]) = "undefined "){
Obj [nodeName] = xmlToJson (item );
} Else {
If (typeof (obj [nodeName]. length) = "undefined "){
Var old = obj [nodeName];
Obj [nodeName] = [];
Obj [nodeName]. push (old );
}
Obj [nodeName]. push (xmlToJson (item ));
}
}
}
Return obj;
};