'@attributes'
を使用してxml2jsonコードの多くのバージョンを見てきました。コードは次のとおりです。なぜ私の質問はobj[attribute.nodeName] = attribute.nodeValue
を使用しないのですか?XMLをJSONに変換するときに '@attributes'を使用する理由
// 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;
};
リンクは、私は今それを知っていたhere
属性を保持するためにattributesプロパティを使用するのが一般的です。通常のHTML DOM要素は、属性がプロパティではないため、 'element.attributes'で同じことを行います。なぜ@記号が使用されているのか分かりませんが、PHPなどの他の言語で何十年もXMLを解析する際にその方法で使用されています。 – adeneo