Reputation: 186
I have seen many versions of the xml2json code using the '@attributes'
, the code is following,my question is why not just use obj[attribute.nodeName] = attribute.nodeValue
?
// 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;
//why not just use obj[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].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
The link is here
Upvotes: 0
Views: 209
Reputation: 146500
The XML format has a wider range of data structures than JSON. A give piece of info can be provided either as node:
<foo>33</foo>
... or as attribute:
<bar foo="33">
On the contrary, JSON provides no other way than object property:
{"foo": 33}
Given this limitation, writers of automated JSON to XML converters need a way to handle this situation and using an arbitrary prefix @
has become the de-facto standard.
Upvotes: 1
Reputation: 186
I knew it now. To distinguish the element attributes and child element attributes . When they equal each other , the trick works.
Like:<tag attr= "Val">
<attr subattr="sub Val "></attr>
</tag>
Upvotes: 0