3

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:

Uncaught TypeError: Object cat.xml has no method 'hasChildNodes'

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

Tool (javascript) to convert a XML string to JSON

and here is a jsbin with what I am trying to do and with the error showing. Thank you.

http://jsbin.com/ujoPECU/1/edit

var xmlToJson = function (xml) {
    'use strict';
    var obj = {};
    if (xml.nodeType == 1) {
        if (xml.attributes.length > 0) {
            obj["@attributes"] = {};
            for (var j = 0; j < 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 < 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);
1
  • As an aside, even if it worked your xmlToJson() function doesn't return JSON, it returns an object (which you seem to already know given you've used JSON.stringify() to get actual JSON from the result). Commented Nov 9, 2013 at 20:49

3 Answers 3

9

The problem is that you're trying to parse the string "cat.xml" as an XML document. I would suggest reading up on XML documents in Javascript but you essentially need to get the contents of your XML file, parse it into an XML document, then run it through your xmlToJson function (which actually returns an object).

var xmlString = "<a><b>C</b></a>";
var parser = new DOMParser();
var xml = parser.parseFromString(xmlString, "text/xml");
var obj = xmlToJson(xml);
Sign up to request clarification or add additional context in comments.

Comments

1

The code snippet you have here looks like it comes from David Walsh's blog at https://davidwalsh.name/convert-xml-json. The xml parameter is supposed to be a Titanium.XML.DOMDocument. So, you can't simply pass in "cat.xml".
I am not sure what the scope of your project was, but I found the rss-to-json Node library helpful for my mobile project.

Comments

0

As Browser-side javascript doesn't have permission to write (and reading XML files doesn't make sense in this case) to the client machine without a lot of security options having to be disabled, you will need to get that XML via HTTP requests to your server.

function XMLDoc(callback){
    if (window.XMLHttpRequest){
        xmlhttp=new XMLHttpRequest();
    }
    else{
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function(){
      //Success
      if (xmlhttp.readyState==4 && xmlhttp.status==200){
        console.log("Response from server : "+xmlhttp.responseText);
        callback(xmlhttp.responseXML); 
      }
};
xmlhttp.open("GET","http://yourServerAddress.com/yourfile.xml",true);
xmlhttp.send();
}

XMLDoc(function(e){
   //Now you can call your function
   var jsonText = JSON.stringify(xmlToJson(e));
   console.log("Converted JSON: "+jsonText);    
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.