Today, I read an article about converting the XML format to the JSON format by David Walsh. It feels good and I simply reprinted it.
The following is the magic javascript code for converting XML to JSON:
// Changes XML to JSON
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;
};
The following XML is:
<Alexa ver = "0.9" URL = "davidwalsh. name/" HOME = "0" AID = "=">
<Sd title = "A" FLAGS = "" HOST = "Davy. name">
<Title text = "David Walsh Blog: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/>
<Linksin num = "1102"/>
<Speed text = "1421" PCT = "51"/>
</SD>
<SD>
<Popularity url = "davidworkshops. name/" TEXT = "7131"/>
<Reach rank = "5952"/>
<Rank delta = "-1648"/>
</SD>
</ALEXA>
The JSON converted by the above function is:
{
"@ Attributes ":{
AID: "= ",
HOME: 0,
URL: "maid. name /",
VER: "0.9 ",
},
SD = [
{
"@ Attributes ":{
FLAGS :"",
HOST: "maid ",
TITLE:
},
LINKSIN :{
"@ Attributes ":{
NUM: 1102
}
},
SPEED :{
"@ Attributes ":{
PCT: 51,
TEXT: 1421
}
},
TITLE :{
"@ Attributes ":{
TEXT: "David Walsh Blog: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else ",
}
},
},
{
POPULARITY :{
"@ Attributes ":{
TEXT: 7131,
URL: "maid. name /"
}
},
RANK :{
"@ Attributes ":{
DELTA: & quot;-1648 & quot"
}
},
REACH :{
"@ Attributes ":{
RANK = 5952
}
}
}
]
}
Original article address: Convert XML to JSON with JavaScript