将 XML 转换为 JSON 时出现未定义的错误

Undefined error converting XML to JSON

本文关键字:未定义 错误 XML 转换 JSON      更新时间:2023-09-26

我正在使用一团代码将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]);

我尝试的变体都会导致未定义。

#text变量

源自 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'])