title: convert xml to json in Javascript
body: <p>I have the following javascript function (which I got from Stack Overflow) which converts XML to JSON:</p>
  
  <pre><code>function xmlToJson(xml) {
      try {
          var obj = {};
          if (xml.nodeType == 1) {
              if (xml.attributes.length &gt; 0) {
                  for (var j = 0; j &lt; xml.attributes.length; j++) {
                      var attribute = xml.attributes.item(j);
  
                      obj[attribute.nodeName] = attribute.nodeValue;
                  }
              }
          } else if (xml.nodeType == 3) {
              obj = xml.nodeValue;
          }
  
          if (xml.hasChildNodes()) {
              for (var i = 0; i &lt; 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));
                  }
              }
          }
  
          console.log(JSON.stringify(obj));
          return obj;
      } catch (e) {
          alert(e.message);
      }
  }
  </code></pre>
  
  <p>What I want is to return it as an array ([]) when a xml node has at-least single child node and it has a parent node also. In this code it returns map ({}) if xml node has single child node but it is fine with multiple child nodes.</p>
  
  <p>For example, I'd like the <em>XML</em></p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;pnode attr1="abc"&gt;
      &lt;cnode attr2="xyz"&gt;&lt;/cnode&gt;
  &lt;/pnode&gt;
  </code></pre>
  
  <p>to be transformed into the <em>JSON</em></p>
  
  <pre class="lang-js prettyprint-override"><code>{
      "pnode": {
          "attr1": "abc"
      },
      "cnode": [
          {"attr2": "xyz"}
      ]
  }
  </code></pre>