如何在 JSX 中将 XML 转换为 JSON 对象?

How to convert XML to JSON object in JSX?

如何将 XML 文件转换为 JSON 对象?

这是 XML 到 JSON 转换的简单代码。

function xmlToJson(xml) {
    // Create the return object
    var obj = {};
    if (xml.nodeKind() == "element") {
        if (xml.attributes().length() > 0) {
            for (var j = 0; j < xml.attributes().length(); j++) {
                var attributeName = xml.attributes()[j].name();
                obj[attributeName] = String(xml.attributes()[j]);
            }
        }
    } else if (xml.nodeKind() == "text") {
        obj['text'] = xml.text();
    }
    if (xml.children()) {
        for (var i = 0; i < xml.children().length(); i++) {
            var item = xml.child(i);
            if (xml.children()[i].nodeKind() == "text") {
                obj['text'] = xml.children()[i].toString();
            } else {
                var nodeName = item.name();
                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;
};