1

Estoy utilizando el siguiente script para convertir un XML en un objeto JSON:

function xmlToJson(xml) {

    var obj = {};

    if (xml.nodeType == 1) { // element
        // do attributes
        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 == 4) { // cdata section
        obj = xml.nodeValue
    }

    // do children

    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].length) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                if (typeof(obj[nodeName]) === 'object') {
                    obj[nodeName].push(xmlToJson(item));
                }
            }
        }
    }
    return obj;
};

Me devuelve el siguiente error en consola:

Uncaught TypeError: xml.hasChildNodes is not a function

El XML es tan simple como este:

<"?xml version="1.0" encoding="utf-8"?>
<animals>
    <dog color='Black'>
        <name>Rufus</name>
        <breed>labrador</breed>
    </dog>
    <dog breed='whippet'>
        Adopted
        <name>Marty</name>
    </dog>
    <cat color="White">
        <name>Matilda</name>
    </cat>
</animals>

¿Qué es lo que estoy haciendo mal para no poder trabajar con el XML?

5
  • xml.hasChildNodes() no lo reconoce como una función el 15 ago. 2017 a las 15:41
  • Puedes editar tu pregunta y agregar de qué manera estás invocando a tu función.
    – Davlio
    el 15 ago. 2017 a las 16:16
  • En la consola de Chrome.
    – kamome
    el 15 ago. 2017 a las 16:19
  • Si lo estás pasando desde un string tal vez necesites usar DOMParser() antes.
    – César
    el 15 ago. 2017 a las 16:23
  • No. Tal cual. Con tags de apertura y cierre. Tal y como está
    – kamome
    el 15 ago. 2017 a las 16:25

2 respuestas 2

1

Debido a que en tu consola estás enviando un objeto diferente a documento XML te arroja dicho error, para ello podrías usar jQuery para realizar conversión.

function xmlToJson(xml) {

    var obj = {};

    if (xml.nodeType == 1) { // element
        // do attributes
        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 == 4) { // cdata section
        obj = xml.nodeValue
    }

    // do children

    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].length) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                if (typeof(obj[nodeName]) === 'object') {
                    obj[nodeName].push(xmlToJson(item));
                }
            }
        }
    }
    return obj;
};

var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><animals><dog color='Black'><name>Rufus</name><breed>labrador</breed></dog><dog breed='whippet'>Adopted<name>Marty</name></dog><cat color=\"White\"><name>Matilda</name></cat></animals>";

console.log(xmlToJson($.parseXML(xml)));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Referencia:

1

El problema que tienes es que la variable xml que pasas a la funcin no es un XML DOM DOC y por lo tanto no tiene la funcion hasChildNodes()

prueba esto:

var text= '<"?xml version="1.0" encoding="utf-8"?>'+
'<animals>'+
    '<dog color="Black">'+
        '<name>Rufus</name>'+
        '<breed>labrador</breed>'+
   ' </dog>'+
    '<dog breed="whippet">'+
        'Adopted'+
        '<name>Marty</name>'+
   ' </dog>'
    '<cat color="White">'+
        '<name>Matilda</name>'+
    '</cat>'+
'</animals>';

 var    parser = new DOMParser();
 var xmlDoc = parser.parseFromString(text,"text/xml");

function xmlToJson(xml) {
  ...
};

console.log(JSON.stringify(xmlToJson(xmlDoc)));
2
  • pero entonces tengo que transformar el xml. antes de pasárselo a la función?
    – kamome
    el 15 ago. 2017 a las 16:42
  • como lo obtienes? mira este ejemplo w3schools.com/xml/tryit.asp?filename=try_dom_loadxmldoc2. lo que si tienes que estar seguro que lo que le pases a la funcion tiene que ser un xml DOM Document
    – jhbosch
    el 15 ago. 2017 a las 17:37

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.