【问题标题】:Undefined error converting XML to JSON将 XML 转换为 JSON 的未定义错误
【发布时间】: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


    【解决方案1】:

    #text-variables 源自 DOM 文本节点 (nodeType = 3),其简写类型为“#text”。

    在我的控制台中,我可以这样做:

    > var x = {};
    < undefined
    > x['#text']= 'abcd';
    < "abcd"
    > x
    < Object { #text: "abcd" }
    > x['#text']
    < "abcd"
    

    所以在你的情况下(我希望我得到对象并且它是孩子的​​权利:

    console.log (objName.Arrayofstring.string[0]['#text'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      • 2016-06-15
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多