Home >Web Front-end >JS Tutorial >Detailed explanation of JS operation of converting xml object into Json object

Detailed explanation of JS operation of converting xml object into Json object

迷茫
迷茫Original
2017-03-26 15:04:581535browse

Recently, when dealing with a front-end function, I encountered a problem. The original system used xml to store data, but on the new system, I wanted to convert it to json object storage, so I considered directly converting it to json object storage. xml object is converted to json object.

So far, I have not found a universal conversion method. I can only use a for loop to continuously assign values ​​based on the known xml object structure.

var xml = ······;//获取xml对象
var objList = [];
for(var i = 0;i<xml.childNodes.length;i++){
    var obj = {};
    obj.attribute1 = xml.getAttribute("attribute1");//获取节点属性
    obj.attribute2 = xml.getAttribute("attribute2");
    obj.children = [];
    for(var x=0;x<xml.childNodes[i].childNodes.length;x++){
        var element = xml.childNodes[i].childNodes[x];
        var child = {};
        child.attribute1 = element.getAttribute("attribute1");
        child.attribute2 = element.getAttribute("attribute2");
        obj.children.push(child);
    }
    objList.push(obj);          
}

The for loop can continue to be nested, and the attributes of each new json object can be customized, but you must fill in the existing attributes you need in the getAttribute() method.

This method seems stupid, so I’ll use it like this for now, and I’ll consider replacing it when I think of a better method.

The above is the detailed content of Detailed explanation of JS operation of converting xml object into Json object. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn