Skip to content

xml2json is undefined #84

@benjaminbillet

Description

@benjaminbillet

Hi all,
After solving the bug of getData (returns always false due to a wrong boolean expression) as described in another issue, I got xml2json is undefined. Indeed xml2json is used in the xml2Object (line 910 and 918) and is not defined anywhere else.

I suspect that the developers depend on something installed on their computers but not provided in the release. Anyway, given the name of the function, I assume that it converts XML data to JSON data (yes, I know, this is a quite clever deduction 😉), so I implemented a new one:

function xml2json(xml) {
  var json = {};

  if (xml.nodeType == 1) { // element node
    if (xml.attributes.length > 0) {
      json['@attributes'] = {};
      for (var j = 0; j < xml.attributes.length; j++) {
        var attribute = xml.attributes.item(j);
        json['@attributes'][attribute.nodeName] = attribute.nodeValue;
      }
    }
  } else if (xml.nodeType == 3) { // text node
    return xml.nodeValue;
  }

  // deal with children
  if (xml.hasChildNodes()) {
    for(var i = 0; i < xml.childNodes.length; i++) {
      var child = xml.childNodes.item(i);
      var nodeName = child.nodeName;
      if (json[nodeName] == null) {
        json[nodeName] = xml2json(child);
      } else {
        if (json[nodeName].push == null) {
          var old = json[nodeName];
          json[nodeName] = [];
          json[nodeName].push(old);
        }
        json[nodeName].push(xml2json(child));
      }
    }
  }
  
  return json;
}

Of course, you are free to use it at your convenience.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions