【发布时间】:2016-02-22 20:02:05
【问题描述】:
我正在使用blob 的代码将 xml 转换为 json:
// Changes XML to JSON
var XmlToJson = function xmlToJson(xml) {
//console.log('called xmltojson');
//console.log(xml);
// Create the return object
var self = this;
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].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
module.exports = XmlToJson;
示例 XML 输入:
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>asdf</string>
<string>123</string>
<string>zxcv</string>
<string>qwer</string>
<string>werty</string>
<string>dfgh</string>
<string>rytui</string>
</ArrayOfstring>
输出:
在 Chrome 控制台中查看我看到的对象:
Object {Arrayofstring: Object}
ArrayOfString: Object
@attributes: Object
string: Array[7]
0: Object
#text: "123"
1: Object
#text: "456"
我在获取 #text 数据时遇到问题。 AFAIK,哈希是变量名中的非法字符。为什么会在那里?如何访问这些#text 变量的值?
我尝试了以下变化:
console.log(myVariable.string[0]);
我尝试的所有变体都导致未定义。
【问题讨论】:
标签: javascript json xml