This article mainly introduces how JavaScript converts XML into JSON. The example analyzes the XML file operation and format conversion techniques in javascript, which has some reference value, for more information about how to convert XML into JSON, see the example in this article. Share it with you for your reference. The specific method is as follows:
1. The JavaScript code is as follows:
The Code is as follows:
// 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;
};
2. XML code:
The Code is as follows:
3. JSON result:
The Code is as follows:
{
"@ 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
}
}
}
]
}
If you are interested in js xml operations, refer to online tools:
Online XML/JSON conversion tools
Online XML formatting/compression tools
I hope this article will help you design javascript programs.