Problem showing XML data in HTML

Asked

Viewed 1,374 times

1

<?xml version="1.0" encoding="ISO-8859-1"?>
<CATALOG>
    <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
</CATALOG>

This is XML code and then I put my HTML.

<html>  
    <head>
      <style>
        table,
        th,
        td {
          border: 1px solid black;
          border-collapse: collapse;
        }
        th,
        td {
          padding: 5px;
        }
      </style>
    </head>

    <body>

      <script>
        if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp = new XMLHttpRequest();
        } else { // code for IE6, IE5
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET", "contactos.xml", false);
        xmlhttp.send();
        xmlDoc = xmlhttp.responseXML;

        document.write("<table><tr><th>Artist</th><th>Title</th></tr>");
        var x = xmlDoc.getElementsByTagName("CD");
        for (i = 0; i < x.length; i++) {
          document.write("<tr><td>");
          document.write(x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue);
          document.write("</td><td>");
          document.write(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
          document.write("</td></tr>");
        }
        document.write("</table>");
      </script>

    </body>
</html>

The problem is that when opening the page and it comes blank, how to solve this?

  • Try to debug with alert("MensagemDeAlerta") in Javascript to see where and if it explodes somewhere.

  • Both codes do not work in Chrome. What would be the problem?

1 answer

-1

Friend, replace your pure Javascript code with another one using jQuery. That way it gets a little more current. Note that you need to call jQuery.js for the code to work :)

<html>  
    <head>
      <style>
        table,
        th,
        td {
          border: 1px solid black;
          border-collapse: collapse;
        }
        th,
        td {
          padding: 5px;
        }
      </style>
    </head>

    <body>
        <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script>

        $(document).ready(function(){

            $.ajax({
                url:       'contactos.xml',
                dataType: 'xml',

                // Caso tenha encontrato o arquivo, leio os dados do xml
                success: function(xml){

                    // Pegando todos os dados dentro da variavel array do arquivo xml
                    $(xml).find('CATALOG').each(function() {

                        var arrayCd = []; // Variavel para armazenar array de palavras e descricao

                        // Pegando todos os dados dentro da variavel option do arquivo xml
                        $(this).find('CD').each(function(){

                            //Mostrando na tela
                            content = "<table width='200'>";
                            content += "<tr><td>Title: </td><td>"+ $(this).find('TITLE').text() +"</td></tr>";
                            content += "<tr><td>Country: </td><td>"+ $(this).find('COUNTRY').text() +"</td></tr>";
                            content += "<tr><td>Company: </td><td>"+ $(this).find('COMPANY').text() +"</td></tr>";
                            content += "<tr><td>Price: </td><td>"+ $(this).find('PRICE').text() +"</td></tr>";
                            content += "<tr><td>Year: </td><td>"+ $(this).find('YEAR').text() +"</td></tr>";
                            content += "<tr><td>Artist: </td><td>"+ $(this).find('ARTIST').text() +"</td></tr>";
                            content += "</table><br />";


                            $("#content").append(content);
                            // Armazenando um array com indice word, description dentro do array arrayCd
                            // Voce pode utilizar esse array para enviar a outra pagina se quiser.
                            arrayCd.push(                         
                                    [ 
                                        { 'TITLE' : $(this).find('TITLE').text(),
                                            'COUNTRY' : $(this).find('COUNTRY').text(),
                                            'COMPANY' : $(this).find('COMPANY').text(),
                                            'PRICE' : $(this).find('PRICE').text(), 
                                            'YEAR' : $(this).find('YEAR').text(),
                                          'ARTIST' : $(this).find('ARTIST').text() }  
                                    ]
                                );
                        });            

                        // Exibindo dados armazenado no array
                        console.log( arrayCd );

                    }); 
                },

                // Se nao consegui ler o arquivo xml, exibo mensagem de erro no console
                error: function () {
                    console.log("Ocorreu um erro inesperado durante o processamento.");
                }
            });

        });


      </script>

    <div id="content"></div>

    </body>
</html>
  • 2

    Thomas, welcome to Sopt. Our community is a little different from forums like you saw on tour. If possible, add more details regarding your response, and.g what has changed and why. Maybe this link from our central be helpful.

  • I made this code in HTML but the result was a blank page. I don’t know if you can help me with this

  • Strange, here it worked... check if the.xml contacts file is in the same folder of that html file and check what is the return that appears in the javascript console

Browser other questions tagged

You are not signed in. Login or sign up in order to post.