由于每个玩家的键都是相同的(code
, position
, countrycode
),因此您不能使用关联数组(在 JavaScript 中,实际上没有,但您可以使用Object
)。您必须使用一组对象。这是我的做法:
var str = '<root><player><roster><player code="AUQ" position="Guard" countrycode="SRB"/><player code="AQX" position="Forward" countrycode="GER"/></roster></player><player><roster><player code="AUQ1" position="Guard" countrycode="SRB"/><player code="AQX1" position="Forward" countrycode="GER"/></roster></player></root>',
oParser = new DOMParser(),
xmlDoc = oParser.parseFromString(str, "text/xml");
var players = xmlDoc.getElementsByTagName("player"),
ret = [], i, j, cur;
for (i = 0, j = players.length; i < j; i++) {
cur = players[i];
if (cur.hasAttribute("code")) {
ret.push({
code: cur.getAttribute("code"),
position: cur.getAttribute("position"),
countrycode: cur.getAttribute("countrycode")
});
}
}
console.log(ret);
演示:http: //jsfiddle.net/2GPBY/1/
如果您想为该键的所有值创建一个键映射,您可以使用以下命令:
var str = '<root><player><roster><player code="AUQ" position="Guard" countrycode="SRB"/><player code="AQX" position="Forward" countrycode="GER"/></roster></player><player><roster><player code="AUQ1" position="Guard" countrycode="SRB"/><player code="AQX1" position="Forward" countrycode="GER"/></roster></player></root>',
oParser = new DOMParser(),
xmlDoc = oParser.parseFromString(str, "text/xml");
var players = xmlDoc.getElementsByTagName("player"),
ret = {}, i, j, cur;
for (i = 0, j = players.length; i < j; i++) {
cur = players[i];
if (cur.hasAttribute("code")) {
if (!("code" in ret)) {
ret.code = [];
}
ret.code.push(cur.getAttribute("code"));
if (!("position" in ret)) {
ret.position = [];
}
ret.position.push(cur.getAttribute("position"));
if (!("countrycode" in ret)) {
ret.countrycode = [];
}
ret.countrycode.push(cur.getAttribute("countrycode"));
}
}
console.log(ret);
演示:http: //jsfiddle.net/2GPBY/3/