Note that there are some explanatory texts on larger screens.

plurals
  1. POXML to JSON javascript function not working
    text
    copied!<p>I pulled this function from another stackoverflow question(link below). I want to be able to convert the XML that I have(included as a HTML comment) to a JSON format. I thought this snippet would work but it keeps giving this error:</p> <p>Uncaught TypeError: Object cat.xml has no method 'hasChildNodes' </p> <p>I still trying wrap my head around javascript so I can't figure this out. I am sorry if this has been answered but I searched and can't find an answer anywhere.Here is the original question</p> <p><a href="https://stackoverflow.com/questions/7769829/tool-javascript-to-convert-a-xml-string-to-json">Tool (javascript) to convert a XML string to JSON</a></p> <p>and here is a jsbin with what I am trying to do and with the error showing. Thank you.</p> <p><a href="http://jsbin.com/ujoPECU/1/edit" rel="nofollow noreferrer">http://jsbin.com/ujoPECU/1/edit</a></p> <pre><code>var xmlToJson = function (xml) { 'use strict'; var obj = {}; if (xml.nodeType == 1) { if (xml.attributes.length &gt; 0) { obj["@attributes"] = {}; for (var j = 0; j &lt; xml.attributes.length; j++) { var attribute = xml.attributes.item(j); obj["@attributes"][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)); } } } return obj; }; var jsonText = JSON.stringify(xmlToJson("cat.xml")); // xmlDoc = xml dom document console.log(jsonText); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload