Necesito leer un archivo donde el contenido está escrito en XML. Quiero convertir el contenido en JSON y luego acceder a sus componentes (sigma, tipo). El problema es que tengo un método para convertir de xml a json, pero creo que no funciona. El código es el siguiente:
function xmlToJson2( xml ) { // Create the return object 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 == 3 ) { // text 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] = xmlToJson2( item ); } else { if ( typeof( obj[nodeName].push ) == "undefined" ) { var old = obj[nodeName]; obj[nodeName] = []; obj[nodeName].push( old ); } obj[nodeName].push( xmlToJson2( item ) ); } } } return obj; };Llamo a ese método de esta manera
let reader2 = new FileReader(); reader2.readAsText(file2); reader2.onloadend = (evt) => { var parser = new DOMParser(); var xmlDoc = parser.parseFromString(evt.target.result,"text/xml"); let stored = JSON.stringify(xmlToJson2(xmlDoc)); this.data.type = stored[0].type; this.data.sigma = stored[0].sigma; this.data.states = stored[0].states; this.data.stack = stored[0].stack; this.data.button = button; let res = filename2.split("."); this.data.filename2 = res[0]; this.parent.dispatchEvent(new CustomEvent('dialog', { detail: { action: 'selection_data', data: this.data } }));evt.target.result es el contenido xml como una cadena
Creo que el método de conversión no funciona porque el contenido json no es como se suponía que debía ser. El primero es el xml y luego la conversión JSON.
¿Que puedo hacer?