Parsing di un file Xml


In questo articolo andremo a vedere come leggere il contenuto di un file xml, supponiamo ad esempio di avere un file xml come il seguente:

<characters>
        <character>
                <name>Pippo</name>
                <address>Topolinia</address>
                <race>Cane antropomorfo</race>
        </character>
        <character>
                <name>Pluto</name>
                <address>Topolinia</address>
                <race>Cane</race>
        </character>
        <character>
                <name>Topolino</name>
                <address>Topolinia</address>
                <race>Topo</race>
        </character>
</characters>
 

che chiameremo characters.xml, e supponiamo di voler stampare in una tabella html i dati contenuti all’interno di questo file xml, dovremo caricare il file xml da javascript, recuperare ogni tag character e stampare il contenuto come riga di una tabella. Di seguito il codice:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>JavaScript XML Parser Example</title>
    <script type="text/javascript">

      var xmlDoc=null;
      var html_table=null;
      var div_handler=null;
     
      function importXML(xml_file)
      {
        if (document.implementation && document.implementation.createDocument)
        {
                xmlDoc = document.implementation.createDocument("", "", null);
                xmlDoc.onload = createTable;
        }
        else if (window.ActiveXObject)
        {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.onreadystatechange = function () {
                        if (xmlDoc.readyState == 4) createTable()
                };
        }
        else
        {
                alert(‘Your browser can\’t handle this script’);
                return;
        }
        xmlDoc.load(xml_file);
      }

      function createTable()
      {
        div_handler=document.getElementById("table");
        html_table="<table border=\"1\">";
        //Get all character
        var x = xmlDoc.getElementsByTagName(‘character’);
        //For all character
        for(i=0;i<x.length;i++) {
          html_table+="<tr>";
          for (j=0;j<x[i].childNodes.length;j++) {
            //If is a tag
            if (x[i].childNodes[j].nodeType == 1) {
              html_table+="<td>";
              html_table+=x[i].childNodes[j].firstChild.nodeValue;
              html_table+="</td>";
            }
          }
          html_table+="</tr>";
        }
        html_table+="</table>";
        div_handler.innerHTML=html_table;
      }

    </script>
  </head>
  <body onload="importXML(’characters.xml’);">
    <div id="table"></div>
  </body>
</html>

Sorgente dell’esempio

Lascia un commento

Categorie

Cerca

Meta