The example in this article describes the way JavaScript converts XML into JSON. Share to everyone for your reference. The specific methods are as follows:
1. The JavaScript code is as follows:
Copy Code code 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:
Copy Code code as follows:
<alexa ver= "0.9" url= "davidwalsh.name/" home= "0" aid= "=" >
<SD title= "A" flags= "" host= "Davidwalsh.name" >
<title text= "David Walsh Blog:: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/>
<linksin num= "1102"/>
<speed text= "1421" pct= "Wuyi"/>
</SD>
<SD>
<popularity url= "davidwalsh.name/" text= "7131"/>
<reach rank= "5952"/>
<rank delta= " -1648"/>
</SD>
</ALEXA>
3. JSON results:
Copy Code code as follows:
{
"@attributes": {
AID: "=",
home:0,
URL: "davidwalsh.name/",
VER: "0.9",
},
SD = [
{
"@attributes": {
FLAGS: "",
HOST: "Davidwalsh.name",
Title:a
},
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: "davidwalsh.name/"
}
},
RANK: {
"@attributes": {
DELTA: "-1648"
}
},
Reach: {
"@attributes": {
RANK = 5952
}
}
}
]
}
About JS Operation XML Interested friends can also refer to the online tools:
On-line Xml/json Mutual conversion tool
Online XML format/compression tools
I hope this article will help you with your JavaScript programming.