Show contents of an XML file in HTML

1

I want to show the content of the XML file that I select in the form with an input, but it does not work for me.

I have tried different ways and I do not give with the key; I tried to return the name of the file after being chosen and if it works, but the content does not get it.

The code is as follows:

<form method="GET" action="" enctype="multipart/form-data" >
    <input type="file" name="archivo"/><br />
    <input type="submit" onclick="loadDoc()" value="Visualizar archivo">
</form>

<br><br>
<table id="demo"></table>

<script>

function loadDoc()
{

    if (window.XMLHttpRequest) {
        // code for modern browsers
        xhttp = new XMLHttpRequest();
    } else {
        // code for old IE browsers
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }


    xhttp.onreadystatechange = function() {

        if(this.readyState == 4 && this.status == 200)
        {

            if(this.responseXML !== null){

                myFuncion(this);    
            }
        }
    };
    xhttp.open("GET","archivo", true);
    xhttp.send();
}


function myFuncion(xml)
{
    //guardo el contenido del archivo en xmlDoc
    var xmlDoc = xml.responseXML;

    //declaro una tabla para mostrar los datos
    var table = "<tr><th>Titulo</th><th>Autor</th></tr>";
    //guardo en la variable X los valores que se encuentren con el Tag Book para recorrer el fichero xml
    var x = xmlDoc.getElementsByTagName("book");

        for (var i = 0; i < x.length; i++) { 

            table += "<tr><td>" +
            x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
            "</td></tr>";
        }
    document.getElementById("demo").innerHTML = table;
}

</script>

The XML file that I have is this:

<?xml-stylesheet type="text/xsl" href="tabla.xsl">

<?xml version="1.0" encoding="utf-8"?>
<bookstore>
<book category="COOKING">
   <title lang="en">Everyday Italian</title>
   <author>Giada De Laurentiis</author>
   <year>2005</year>
   <price>30.00</price>
</book>
<book category="CHILDREN">
   <title lang="en">Harry Potter</title>
   <author>J K. Rowling</author>
   <year>2005</year>
   <price>29.99</price>
</book>
</bookstore>
    
asked by jm95 08.11.2018 в 21:13
source

1 answer

0

You are doing an unnecessary submit and lacking in functionality. The only thing you have to do is:

  • Load the XML file into memory.
  • Read the file.
  • Parse the contents of the file to document .
  • Extract the data from the new document.
  • To read the file, simply create an instance of FileReader and use the readAsText method, passing it as a parameter the Blob that represents the selected file.

    To parse the file we only need to instantiate DOMParser and use the parseFromString method to which we pass two parameters: the plain text and its corresponding mime type.

    Complete example

    function loadDoc(e) {
      const file = e.target.files[0];
      
      if (!file) {
      	throw new Error('You need to choose an XML file first')
        alert('You need to choose an XML file first')
        return false
      }
      
      readDoc(file).then(parseDoc).then(showDocInTable).catch(onError)
    }
    
    function readDoc(file) {
    	const reader = new FileReader()
      
      return new Promise((ok) => {
      	reader.readAsText(file)
        reader.onload = function() {
          ok(reader.result)
        }
      })
    }
    
    function parseDoc(rawXML) {
    	const parser = new DOMParser()
    	const xml = parser.parseFromString(rawXML, 'text/html')
      return xml
    }
    
    function showDocInTable(xml) {
    	const table = document.querySelector('#bookTable > tbody')
      const datasource = xml.querySelector('bookstore')
      const books = datasource.querySelectorAll('book')
      
      table.removeChild(table.children[0])
    	
      Array.from(books).map((book, i) => {
      	const tr = document.createElement('tr')
      	const title = tagToData(book.querySelector('title'))
        const author = tagToData(book.querySelector('author'))
        const year = tagToData(book.querySelector('year'))
        const price = tagToData(book.querySelector('price'))
        
        tr.append(title, author, year, price)
        table.appendChild(tr)
      })
    }
    
    function tagToData(tag) {
    	const td = document.createElement('td')
      td.textContent = tag.textContent
      return td
    }
    
    function onError(reason) {
    	console.error(reason)
    }
    html {
      box-sizing: border-box;
    }
    *, *:before, *:after {
      box-sizing: inherit;
      margin: 0;
      padding: 0;
    }
    body {
      font-family: Helvetica, sans-serif, arial;
      padding: 50px;
      display: grid;
      grid-template-columns: 40% 60%;
      grid-gap: 0 20px;
    }
    #bookForm {
      align-items: center;
      background-color: #f8f8f8;
      display: flex;
      justify-content: center;
      padding: 8px;
    }
    #bookForm input {
      display: none;
    }
    #bookForm label {
      background-color: #00AF3F;
      border-radius: 25px;
      box-shadow: 0 2px 3px 0 rgba(0,0,0,.1);
      color: #fff;
      cursor: pointer;
      display: inline-block;
      font-size: 14px;
      font-weight: 200;
      height: 35px;
      line-height: 35px;
      padding: 0 20px;
    }
    #bookTable {
      border-collapse: collapse;
      border: 1px solid #e5e5e5;
    }
    #bookTable td,
    #bookTable th {
      color: #444;
      font-size: 14px;
      padding: 15px 15px;
    }
    #bookTable thead {
      border-bottom: 2px solid #ddd;
    }
    #bookTable thead th {
      background-color: #f5f5f5;
    }
    #bookTable tbody {
      padding: 10px;
    }
    #bookTable tbody tr:not(:last-child) {
      border-bottom: 1px solid #eee;
    }
    #bookTable tbody td:not(:last-child) {
      border-right: 1px solid #eee;
    }
    <div id="bookForm">
        <input id="books" type="file" onChange="loadDoc(event)">
        <label for="books">Cargar archivo</label>
    </div>
    
    <table id="bookTable">
      <thead>
        <tr>
          <th>Autor</th>
          <th>Título</th>
          <th>Año</th>
          <th>Precio</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td colspan="4" style="text-align: center">Sin registros</td>
        </tr>
      </tbody>
    </table>
        
    answered by 08.11.2018 / 22:38
    source