Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

231
Vistas
Llenar una tabla HTML desde un XML externo

Me encontré con un problema al obtener datos de un documento XML externo con JS. He estado siguiendo el tutorial de w3schools para AJAX XML hasta ahora, pero encontré algo que no pude resolver. Tengo un XML que se ve así:

 <root> <document-id> <author>Tom Riddle</autor> <title>abzy</title> <year>1995</year> </document-id> <document-id> <author>Tom Riddle</autor> <title>abzy</title> </document-id> <document-id> <author>Tom Riddle</autor> <year>1995</year> </document-id> </root>

Quiero acceder dinámicamente a los datos dentro del XML y crear una tabla mientras lo hago. Funciona bien para el único elemento DOM que comparten todos los documentos, pero me da un error tan pronto como incluyo el año o el título. Supongo que es porque las etiquetas están vacías en algunas partes del árbol. ¿Hay alguna manera de ignorar las etiquetas vacías y solo escribir algo en la columna si hay un valor dentro? Gracias por su tiempo y conocimiento.

ESTE ES EL HTML ASOCIADO

 <body> <header> <h1>Reading Data from XML Files</h1> </header> <main> <button type="button" onclick="loadDoc()">Get my CD collection</button> <table id="demo"> </table> </main> <script> function loadDoc() { const xhttp = new XMLHttpRequest(); xhttp.onload = function() { myFunction(this); } xhttp.open("GET", "books.xml"); xhttp.send(); } function myFunction(xml) { const xmlDoc = xml.responseXML; const x = xmlDoc.getElementsByTagName("document-id"); console.log(x) let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>"; for (let i = 0; i <x.length; i++) { table += "<tr><td>" + x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue + "</tr>"; } document.getElementById("demo").innerHTML = table; } </script> </body>
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Verifique la existencia antes de intentar acceder a los niños.

 function getText(node, tag) { var elem = node.getElementsByTagName(tag); return elem ? elem.[0].childNodes[0].nodeValue : ''; } for (let i = 0; i <x.length; i++) { var cells = ['author', 'title', 'year'].map(function (tag) { return "<td>" + getText(x[i], tag) + "</td>"; }).join(""); table += "<tr>" + cells + "</tr>"); }
about 4 years ago · Juan Pablo Isaza Denunciar

0

intente esto con una solución en línea para verificar si existe una etiqueta en xml

 function myFunction(xml) { const xmlDoc = xml.responseXML; const x = xmlDoc.getElementsByTagName("document-id"); console.log(x) let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>"; for (let i = 0; i <x.length; i++) { table += "<tr><td>" + x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue + "</td><td>" + ((x[i].getElementsByTagName("title")[0] == undefined)?"": x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue ) + "</td><td>" + ((x[i].getElementsByTagName("year")[0] == undefined)?"": x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue ) + "</tr>"; } document.getElementById("demo").innerHTML = table; }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda