Lea el archivo XML e imprima los detalles como datos tabulares usando JavaScript

Introducción: para leer el archivo XML e imprimir los detalles de un archivo XML en forma tabular usando javaScript. Necesitamos crear un archivo XML cuyos datos queremos imprimir. XML significa Extensible Markup Language · Es un lenguaje de marcado muy similar a HTML. El propósito principal del archivo XML está diseñado para almacenar y transportar los datos. Crear un archivo XML es muy simple porque utiliza etiquetas personalizadas.

requisitos previos:

Enfoque: después de crear el archivo XML, escribiremos JavaScript para leer y extraer datos del archivo en forma tabular. Entonces, enviaremos XMLHttpRequest al servidor y buscaremos los detalles del archivo XML usando JavaScript. Si la solicitud finaliza, la respuesta está lista y el Estado es «OK», por lo que obtenemos los datos XML mediante el uso del Nombre de la etiqueta.

Ahora vamos a crear dos archivos:

1.employee.xml: un archivo xml que almacena los detalles del empleado. Para crear un archivo xml usamos etiquetas personalizadas, aquí usamos diferentes etiquetas personalizadas como el nombre, apellido, título, división, etc. que almacenan los detalles de cada empleado de acuerdo con el nombre de la etiqueta.

employee.xml

<?xml version="1.0" encoding="utf-8"?>
<employees>
    <employee id="be129">
        <firstname>Jitendra</firstname>
        <lastname>Kumar</lastname>
        <title>Engineer</title>
        <division>Materials</division>
        <building>327</building>
        <room>19</room>
    </employee>
    <employee id="be130">
        <firstname>Amit</firstname>
        <lastname>Kumar</lastname>
        <title>Accountant</title>
        <division>Accts Payable</division>
        <building>326</building>
        <room>14</room>
    </employee>
    <employee id="be131">
        <firstname>Akash</firstname>
        <lastname>Kumar</lastname>
        <title>Engineering Manager</title>
        <division>Materials</division>
        <building>327</building>
        <room>21</room>
    </employee>
    <employee id="be132">
        <firstname>Aishwarya</firstname>
        <lastname>Kulshrestha</lastname>
        <title>Engineer</title>
        <division>Materials</division>
        <building>327</building>
        <room>22</room>
    </employee>
    <employee id="be133">
        <firstname>Sachin</firstname>
        <lastname>Kumar</lastname>
        <title>Engineer</title>
        <division>Materials</division>
        <building>327</building>
        <room>24</room>
    </employee>
    <employee id="be135">
        <firstname>Vikash</firstname>
        <lastname>kumar</lastname>
        <title>COO</title>
        <division>Management</division>
        <building>216</building>
        <room>26</room>
    </employee>
    <employee id="be136">
        <firstname>Suvam</firstname>
        <lastname>Basak</lastname>
        <title>Accountant</title>
        <division>Accts Payable</division>
        <building>326</building>
        <room>30</room>
    </employee>
    <employee id="be135">
        <firstname>Abhinav</firstname>
        <lastname>kumar</lastname>
        <title>COO</title>
        <division>Management</division>
        <building>216</building>
        <room>32</room>
    </employee>
     <employee id="be131">
        <firstname>DhanPal</firstname>
        <lastname>Singh</lastname>
        <title>Engineering Manager</title>
        <division>Materials</division>
        <building>327</building>
        <room>21</room>
    </employee>
  
</employees>

2.index.html: este archivo contiene el código HTML, CSS y JavaScript. Usamos la etiqueta de estilo para la parte CSS en la que estamos diseñando el atributo de la tabla y el botón, luego usamos la etiqueta de script en la que escribimos el código JavaScript e insertamos el archivo employee.xml. En la función loadXMLDoc( ), enviamos la solicitud HTTP al servidor cuando finaliza la solicitud, luego obtenemos la respuesta del servidor y accedemos a los datos desde un archivo XML. En la función empDetails(), si obtenemos la respuesta del servidor, buscamos los datos del archivo XML uno por uno usando el nombre de la etiqueta personalizada. Para mostrar los datos de este archivo xml, simplemente haga clic en el botón Obtener detalles de los empleados y los datos del archivo xml se mostrarán en su pantalla en forma tabular.

index.html

<!DOCTYPE html>
  
<head>
    <title>Reads the XML data using JavaScript</title>
  
    <!-- CSS -->
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }
  
        th,
        td {
            text-align: left;
            padding: 8px;
        }
  
        tr:nth-child(even) {
            background-color: #7ce2af
        }
  
        th {
            background-color: #7c0f65;
            color: white;
        }
  
        .button {
            position: relative;
            text-align: center;
            padding: 20px;
            border: 4px solid rgb(55, 12, 211);
            background: rgba(20, 192, 4, 0.5);
            color: rgb(230, 36, 78);
            outline: none;
            border-radius: 30px;
            font-size: 30px;
            width: 500px;
  
        }
  
        .button:hover {
            color: black;
            background: white;
        }
    </style>
  
    <!--JavaScript-->
    <script>
        function loadXMLDoc() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {
  
                // Request finished and response 
                // is ready and Status is "OK"
                if (this.readyState == 4 && this.status == 200) {
                    empDetails(this);
                }
            };
  
            // employee.xml is the external xml file
            xmlhttp.open("GET", "employee.xml", true);
            xmlhttp.send();
        }
  
        function empDetails(xml) {
            var i;
            var xmlDoc = xml.responseXML;
            var table =
                `<tr><th>Firstname</th><th>Lastname</th>
                    <th>Title</th><th>Division</th>
                    <th>Building</th><th>Room</th>
                </tr>`;
            var x = xmlDoc.getElementsByTagName("employee");
  
            // Start to fetch the data by using TagName 
            for (i = 0; i < x.length; i++) {
                table += "<tr><td>" +
                    x[i].getElementsByTagName("firstname")[0]
                    .childNodes[0].nodeValue + "</td><td>" +
                    x[i].getElementsByTagName("lastname")[0]
                    .childNodes[0].nodeValue + "</td><td>" +
                    x[i].getElementsByTagName("title")[0]
                    .childNodes[0].nodeValue + "</td><td>" +
                    x[i].getElementsByTagName("division")[0]
                    .childNodes[0].nodeValue + "</td><td>" +
                    x[i].getElementsByTagName("building")[0]
                    .childNodes[0].nodeValue + "</td><td>" +
                    x[i].getElementsByTagName("room")[0]
                    .childNodes[0].nodeValue + "</td></tr>";
            }
  
            // Print the xml data in table form
            document.getElementById("id").innerHTML = table;
        }
    </script>
</head>
  
<body>
    <center>
        <button type="button" class="button" 
            onclick="loadXMLDoc()">
            Get Employees Details
        </button>
    </center>
      
    <br><br>
    <table id="id"></table>
</body>
  
</html>

Pasos para ejecutar la aplicación: Para leer los datos XML necesitamos ejecutar este código en el servidor local Entonces, primero iniciamos el servidor local y luego de que abre el navegador Chrome, iniciamos el host local y vemos los resultados. Después de hacer clic en el botón obtener detalles de los empleados, obtendremos los detalles de los empleados en forma tabular.

Producción:

Publicación traducida automáticamente

Artículo escrito por gangwarjacob y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *