Javascript code conversion from xml to json _ javascript skills

Source: Internet
Author: User
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;
};

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.