Convert XML to JSON (and back) using Javascript

后端 未结 12 1369
Happy的楠姐
Happy的楠姐 2020-11-22 03:18

How would you convert from XML to JSON and then back to XML?

The following tools work quite well, but aren\'t completely consistent:

  • xml2json
12条回答
  •  死守一世寂寞
    2020-11-22 03:29

    These answers helped me a lot to make this function:

    function xml2json(xml) {
      try {
        var obj = {};
        if (xml.children.length > 0) {
          for (var i = 0; i < xml.children.length; i++) {
            var item = xml.children.item(i);
            var nodeName = item.nodeName;
    
            if (typeof (obj[nodeName]) == "undefined") {
              obj[nodeName] = xml2json(item);
            } else {
              if (typeof (obj[nodeName].push) == "undefined") {
                var old = obj[nodeName];
    
                obj[nodeName] = [];
                obj[nodeName].push(old);
              }
              obj[nodeName].push(xml2json(item));
            }
          }
        } else {
          obj = xml.textContent;
        }
        return obj;
      } catch (e) {
          console.log(e.message);
      }
    }
    

    As long as you pass in a jquery dom/xml object: for me it was:

    Jquery(this).find('content').eq(0)[0]
    

    where content was the field I was storing my xml in.

提交回复
热议问题