Convert XML to HTML
<source lang="html4strict">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Convert XML to HTML</title>
<style rel="stylesheet" id="mainStyle" type="text/css">
html {background-color:#cccccc}
body {background-color:#eeeeee; font-family:Tahoma,Arial,Helvetica,sans-serif; font-size:12px;
margin-left:15%; margin-right:15%; border:3px groove darkred; padding:15px}
h1 {text-align:right; font-size:1.5em; font-weight:bold}
h2 {text-align:left; font-size:1.1em; font-weight:bold; text-decoration:underline}
.buttons {margin-top:10px}
</style>
<style type="text/css">
table {table-collapse:collapse; border-spacing:0}
td {border:2px groove black; padding:7px; background-color:#ccffcc}
th {border:2px groove black; padding:7px; background-color:#ffffcc}
.ctr {text-align:center}
</style>
<script type="text/javascript">
var xDoc;
// verify that browser supports XML features and load external .xml file
function verifySupport(xFile) {
if (document.implementation && document.implementation.createDocument) {
// this is the W3C DOM way, supported so far only in NN6+
xDoc = document.implementation.createDocument("", "theXdoc", null);
} else if (typeof ActiveXObject != "undefined") {
// make sure real object is supported (sorry, IE5/Mac)
if (document.getElementById("msxml").async) {
xDoc = new ActiveXObject("Msxml.DOMDocument");
}
}
if (xDoc && typeof xDoc.load != "undefined") {
// load external file (from same domain)
xDoc.load(xFile);
return true;
} else {
var reply = confirm("This example requires a browser with XML support, " +
"such as IE5+/Windows or Netscape 6+.\n \nGo back to previous page?");
if (reply) {
history.back();
}
}
return false;
}
// Draw table from xDoc document tree data
function drawTable(tbody) {
var tr, td, i, j, oneRecord;
tbody = document.getElementById(tbody);
// node tree
var data = xDoc.getElementsByTagName("worldcup")[0];
// for td class attributes
var classes = ["ctr","","","","ctr"];
for (i = 0; i < data.childNodes.length; i++) {
// use only 1st level element nodes to skip 1st level text nodes in NN
if (data.childNodes[i].nodeType == 1) {
// one final match record
oneRecord = data.childNodes[i];
tr = tbody.insertRow(tbody.rows.length);
td = tr.insertCell(tr.cells.length);
td.setAttribute("class",classes[tr.cells.length-1]);
td.innerHTML =
oneRecord.getElementsByTagName("year")[0].firstChild.nodeValue;
td = tr.insertCell(tr.cells.length);
td.setAttribute("class",classes[tr.cells.length-1]);
td.innerHTML =
oneRecord.getElementsByTagName("location")[0].firstChild.nodeValue;
td = tr.insertCell(tr.cells.length);
td.setAttribute("class",classes[tr.cells.length-1]);
td.innerHTML =
oneRecord.getElementsByTagName("winner")[0].firstChild.nodeValue;
td = tr.insertCell(tr.cells.length);
td.setAttribute("class",classes[tr.cells.length-1]);
td.innerHTML =
oneRecord.getElementsByTagName("loser")[0].firstChild.nodeValue;
td = tr.insertCell(tr.cells.length);
td.setAttribute("class",classes[tr.cells.length-1]);
td.innerHTML =
oneRecord.getElementsByTagName("winscore")[0].firstChild.nodeValue +
" - " +
oneRecord.getElementsByTagName("losscore")[0].firstChild.nodeValue;
}
}
}
function init(xFile) {
// confirm browser supports needed features and load .xml file
if (verifySupport(xFile)) {
// let file loading catch up to execution thread
setTimeout("drawTable("matchData")", 1000);
}
}
</script>
</head>
<body onload="init("worldCupFinals.xml")">
Transforming XML into HTML Tables
<thead>
Year |
Host Country |
Winner |
Loser |
Score (Win - Lose) |
</thead>
<tbody id="matchData"></tbody>
<object id="msxml" WIDTH="1" HEIGHT="1"
classid="CLSID:2933BF90-7B36-11d2-B20E-00C04F983E60" ></object>
</body>
</html>
</source>
Display XML content in HTML table
<source lang="html4strict">
<html>
<head>
<title>Embedding External XML Data</title>
<style type="text/css">
body {background-color:#ffffff}
table {table-collapse:collapse; border-spacing:0}
td {border:2px groove black; padding:7px}
th {border:2px groove black; padding:7px}
.ctr {text-align:center}
</style>
<script language="JavaScript" type="text/javascript">
// global reference to XML document object
var xDoc;
// Draw table from xDoc document tree data
function drawTable(tbody) {
var tr, td, i, j, oneRecord;
tbody = document.getElementById(tbody);
// node tree
var data = xDoc.getElementsByTagName("season")[0];
// for td class attributes
var classes = ["ctr","","","","ctr"];
for (i = 0; i < data.childNodes.length; i++) {
// use only 1st level element nodes
if (data.childNodes[i].nodeType == 1) {
// one bowl record
oneRecord = data.childNodes[i];
tr = tbody.insertRow(tbody.rows.length);
td = tr.insertCell(tr.cells.length);
td.setAttribute("class",classes[tr.cells.length-1]);
td.innerHTML = oneRecord.getElementsByTagName("number")[0].firstChild.nodeValue;
td = tr.insertCell(tr.cells.length);
td.setAttribute("class",classes[tr.cells.length-1]);
td.innerHTML = oneRecord.getElementsByTagName("year")[0].firstChild.nodeValue;
td = tr.insertCell(tr.cells.length);
td.setAttribute("class",classes[tr.cells.length-1]);
td.innerHTML = oneRecord.getElementsByTagName("winner")[0].firstChild.nodeValue;
td = tr.insertCell(tr.cells.length);
td.setAttribute("class",classes[tr.cells.length-1]);
td.innerHTML = oneRecord.getElementsByTagName("loser")[0].firstChild.nodeValue;
td = tr.insertCell(tr.cells.length);
td.setAttribute("class",classes[tr.cells.length-1]);
td.innerHTML = oneRecord.getElementsByTagName("winscore")[0].firstChild.nodeValue + " - " + oneRecord.getElementsByTagName("losscore")[0].firstChild.nodeValue;
}
}
}
// verify that browser supports XML features and load external .xml file
function verifySupport(xFile) {
if (document.implementation && document.implementation.createDocument) {
// this is the W3C DOM way, supported so far only in NN6
xDoc = document.implementation.createDocument("", "theXdoc", null);
} else if (typeof ActiveXObject != "undefined") {
// make sure real object is supported (sorry, IE5/Mac)
if (document.getElementById("msxml").async) {
xDoc = new ActiveXObject("Msxml.DOMDocument");
}
}
if (xDoc && typeof xDoc.load != "undefined") {
// load external file (from same domain)
xDoc.load(xFile);
return true;
} else {
var reply = confirm("This example requires a browser with XML support, such as IE5+/Windows or Netscape 6+.\n \nGo back to previous page?");
if (reply) {
history.back();
}
}
return false;
}
// initialize first time -- invoked onload
function init(xFile) {
// confirm browser supports needed features and load .xml file
if (verifySupport(xFile)) {
// let file loading catch up to execution thread
setTimeout("drawTable("bowlData")", 1000);
}
}
</script>
</head>
<body onload="init("superBowls.xml");">
Super Bowl Games
<thead>
Bowl |
Year |
Winner |
Loser |
Score (Win or Lose) |
</thead>
<tbody id="bowlData"></tbody>
<object id="msxml" WIDTH="1" HEIGHT="1" classid="CLSID:2933BF90-7B36-11d2-B20E-00C04F983E60" ></object>
</body>
</html>
</source>
function loads the XML document from the specified URL
<source lang="html4strict">
/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition
Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan. You may use, study, modify, and
distribute them for any purpose. Please note that these examples are
provided "as-is" and come with no warranty of any kind.
David Flanagan
<head><title>Employee Data</title>
<script>
// This function loads the XML document from the specified URL, and when
// it is fully loaded, passes that document and the url to the specified
// handler function. This function works with any XML document
function loadXML(url, handler) {
// Use the standard DOM Level 2 technique, if it is supported
if (document.implementation && document.implementation.createDocument) {
// Create a new Document object
var xmldoc = document.implementation.createDocument("", "", null);
// Specify what should happen when it finishes loading
xmldoc.onload = function() { handler(xmldoc, url); }
// And tell it what URL to load
xmldoc.load(url);
}
// Otherwise use Microsoft"s proprietary API for Internet Explorer
else if (window.ActiveXObject) {
var xmldoc = new ActiveXObject("Microsoft.XMLDOM"); // Create doc.
xmldoc.onreadystatechange = function() { // Specify onload
if (xmldoc.readyState == 4) handler(xmldoc, url);
}
xmldoc.load(url); // Start loading!
}
}
// This function builds an HTML table of employees from data it reads from
// the XML document it is passed.
function makeTable(xmldoc, url) {
// Create a
object and insert it into the document.
var table = document.createElement("table");
table.setAttribute("border", "1");
document.body.appendChild(table);
// Use convenience methods of HTMLTableElement and related interfaces
// to define a table caption and a header that gives a name to each column.
var caption = "Employee Data from " + url;
table.createCaption().appendChild(document.createTextNode(caption));
var header = table.createTHead();
var headerrow = header.insertRow(0);
headerrow.insertCell(0).appendChild(document.createTextNode("Name"));
headerrow.insertCell(1).appendChild(document.createTextNode("Job"));
headerrow.insertCell(2).appendChild(document.createTextNode("Salary"));
// Now find all <employee> elements in our xmldoc document
var employees = xmldoc.getElementsByTagName("employee");
// Loop through these employee elements
for(var i = 0; i < employees.length; i++) {
// For each employee, get name, job, and salary data using standard DOM
// methods. The name comes from an attribute. The other values are
// in Text nodes within <job> and <salary> tags.
var e = employees[i];
var name = e.getAttribute("name");
var job = e.getElementsByTagName("job")[0].firstChild.data;
var salary = e.getElementsByTagName("salary")[0].firstChild.data;
// Now that we have the employee data, use methods of the table to
// create a new row and then use the methods of the row to create
// new cells containing the data as text nodes.
var row = table.insertRow(i+1);
row.insertCell(0).appendChild(document.createTextNode(name));
row.insertCell(1).appendChild(document.createTextNode(job));
row.insertCell(2).appendChild(document.createTextNode(salary));
}
}
</script>
</head>
<body onload="loadXML(location.search.substring(1), makeTable)">
</body>
</source>
Loads a XML file and permits to access to the data it contains
<source lang="html4strict">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>JsLib 1.3 - Exemple - xml.js</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<META NAME="Author" CONTENT="Etienne CHEVILLARD">
<SCRIPT TYPE="text/javascript" LANGUAGE="Javascript">
/* xml.js
* Role : charge un fichier XML et permet d"acceder aux donnees qu"il contient
* Projet : JsLib
* Auteur : Etienne CHEVILLARD (echevillard@users.sourceforge.net)
* Version : 1.3
* Creation : 20/08/2004
* Mise a jour : 23/02/2005
* Bogues connues : - Opera 7 ignore les commentaires du fichier XML
*/
// --- Variables globales ---
// chargement du fichier XML
var xml_charge=false;
var xml_doc;
// --- Fonctions ---
// supprime les espaces qui commencent ou qui terminent la chaine specifiee
function xml_suppEsp(chaine) {
var xdeb;
var xfin;
xdeb=chaine;
xfin=chaine;
for(var i=0; ((i<xdeb.length) && (xdeb.charAt(i)==" ")); i++) {
xfin=xfin.substring(1, xfin.length);
}
xdeb=xfin;
for(var i=xdeb.length-1; ((i>=0) && (xdeb.charAt(i)==" ")); i--)
xfin=xfin.substring(0, xfin.length-1);
return (xfin);
} // fin forms_suppEsp(chaine)
// indique si le navigateur accepte le XML
function accepteXML() {
return ((document.implementation && document.implementation.hasFeature && document.implementation.hasFeature("XML", "1.0"))
|| (document.implementation && document.implementation.createDocument)
|| (window.XMLHttpRequest)
|| (window.ActiveXObject)
|| (document.createElement && document.childNodes));
} // fin accepteXML()
// charge en memoire le fichier XML d"URL specifiee
function chargerFichierXML(url) {
if ((!url) || (url=="")) return false;
xml_charge=false;
try {
// implementation conforme au DOM du W3C (Firefox, Mozilla, Netscape)
if (document.implementation && document.implementation.createDocument) {
xml_doc=document.implementation.createDocument("", "", null);
xml_doc.onload=function () { xml_charge=true; }
xml_doc.load(url);
// implementation avec objet XMLHttpRequest
} else if (window.XMLHttpRequest) {
xml_doc=new XMLHttpRequest();
xml_doc.onreadystatechange=function () { if (xml_doc.readyState==4) xml_charge=true; }
xml_doc.open("GET", url, true);
xml_doc.send(null);
// implementation avec ActiveX (Internet Explorer)
} else if (window.ActiveXObject) {
xml_doc=new ActiveXObject("Microsoft.XMLDOM");
xml_doc.onreadystatechange=function () { if (xml_doc.readyState==4) xml_charge=true; }
xml_doc.load(url);
// implementation avec un objet IFRAME et une division cachee (Opera 7)
} else if (document.createElement && document.childNodes) {
var ndiv=document.createElement("DIV");
ndiv.id="jslib_xml_div";
ndiv.style.position="absolute";
ndiv.style.visibility="hidden";
ndiv.innerHTML = "<iframe onLoad=\"xml_doc=window.frames.jslib_xml_ifr.window.document; xml_charge=true;\""
+ " name=\"jslib_xml_ifr\" src=\"" + url + "\"><\/iframe>";
document.body.appendChild(ndiv);
} else {
return false;
}
} catch (e) {
return false;
}
return true;
} // fin chargerFichierXML(url)
// compte le nombre de noeuds XML de nom specifie
function compterNoeuds(nomNoeud) {
if (!xml_charge) return 0;
if ((!nomNoeud) || (nomNoeud=="")) return 0;
var elts=xml_doc.getElementsByTagName(nomNoeud);
return (parseInt(elts.length));
} // fin compterNoeuds(nomNoeud)
// retourne les commentaires du document XML
function obtenirCommentaires() {
if (!xml_charge) return "";
var elts=xml_doc.childNodes;
var txt="";
if (elts.length<1) return txt;
for (var i=0; i<elts.length; i++) {
if (parseInt(elts[i].nodeType)==8) {
if (txt!="") txt+="\n";
txt+=xml_suppEsp(elts[i].nodeValue);
}
}
return txt;
} // fin obtenirCommentaires()
// retourne le premier noeud XML de nom et de valeur specifies
function obtenirNoeud(nomNoeud, valeurNoeud) {
if (!xml_charge) return;
if ((!nomNoeud) || (nomNoeud=="")) return;
var elts=xml_doc.getElementsByTagName(nomNoeud);
if (elts.length<1) return;
for (var i=0; i<elts.length; i++) {
if (parseInt(elts[i].nodeType)==1) {
if ((!valeurNoeud) || (obtenirValeurNoeud(elts[i])==valeurNoeud))
return (elts[i]);
}
}
return;
} // fin obtenirNoeud(nomNoeud, valeurNoeud)
// retourne le noeud fils de nom specifie du noeud XML passe en parametre
function obtenirNoeudFils(noeud, nomFils) {
if (!xml_charge) return;
if (!noeud) return;
if ((!nomFils) || (nomFils=="")) return;
var elts=noeud.childNodes;
if (elts.length<1) return;
for (var i=0; i<elts.length; i++) {
if ((parseInt(elts[i].nodeType)==1)
&& (obtenirNomNoeud(elts[i])==nomFils))
return elts[i];
}
return;
} // fin obtenirNoeudFils(noeud, nomFils)
// retourne le noeud pere du noeud XML passe en parametre
function obtenirNoeudPere(noeud) {
if (!xml_charge) return;
if (!noeud) return;
if (noeud.parentNode) return (noeud.parentNode);
return;
} // fin obtenirNoeudPere(noeud)
// retourne le noeud XML racine du document XML
function obtenirNoeudRacine() {
if (!xml_charge) return;
var elts=xml_doc.childNodes;
if (elts.length<1) return;
for (var i=0; i<elts.length; i++) {
if (parseInt(elts[i].nodeType)==1)
return(elts[i]);
}
return;
} // fin obtenirNoeudRacine()
// retourne le nom du noeud XML passe en parametre
function obtenirNomNoeud(noeud) {
if (!xml_charge) return "";
if (!noeud) return "";
if (noeud.nodeName) return (noeud.nodeName);
if (noeud.name) return (noeud.name);
return "";
} // fin obtenirNomNoeud(noeud)
// retourne la valeur de l"attribut specifie du noeud XML passe en parametre
function obtenirValeurAttribut(noeud, attribut) {
if (!xml_charge) return "";
if (!noeud) return "";
if ((!attribut) || (attribut=="")) return "";
if (noeud.getAttribute(attribut)) return noeud.getAttribute(attribut);
if (noeud.attributes[attribut]) return noeud.attributes[attribut].value;
return "";
} // fin obtenirValeurAttribut(noeud, attribut)
// retourne la valeur du noeud XML passe en parametre
function obtenirValeurNoeud(noeud) {
if (!xml_charge) return "";
if ((!noeud) || (!noeud.firstChild)) return "";
if (noeud.firstChild.nodeValue) return (xml_suppEsp(noeud.firstChild.nodeValue));
if (noeud.firstChild.data) return (xml_suppEsp(noeud.firstChild.data));
return "";
} // fin obtenirValeurNoeud(noeud)
// retourne le premier noeud XML dont la valeur contient la chaine specifiee
function rechercherNoeud(nomNoeud, valeurNoeud) {
if (!xml_charge) return;
if ((!nomNoeud) || (nomNoeud=="")) return;
if (!valeurNoeud) valeurNoeud="";
var elts=xml_doc.getElementsByTagName(nomNoeud);
if (elts.length<1) return;
for (var i=0; i<elts.length; i++) {
if (parseInt(elts[i].nodeType)==1) {
if (obtenirValeurNoeud(elts[i]).toLowerCase().indexOf(valeurNoeud.toLowerCase())>=0)
return (elts[i]);
}
}
return;
} // fin rechercherNoeud(nomNoeud, valeurNoeud)
// retourne le premier noeud XML dont l"attribut specifie contient la chaine specifiee
function rechercherNoeudParAttribut(nomNoeud, attribut, valeurAttribut) {
if (!xml_charge) return;
if ((!nomNoeud) || (nomNoeud=="")) return;
if ((!attribut) || (attribut=="")) return;
if (!valeurAttribut) valeurAttribut="";
var elts=xml_doc.getElementsByTagName(nomNoeud);
if (elts.length<1) return;
for (var i=0; i<elts.length; i++) {
if (parseInt(elts[i].nodeType)==1) {
if (obtenirValeurAttribut(elts[i], attribut).toLowerCase().indexOf(valeurAttribut.toLowerCase())>=0)
return (elts[i]);
}
}
return;
} // fin rechercherNoeudParAttribut(nomNoeud, attribut, valeurAttribut)
// verifie que le fichier XML est totalement charge en memoire
function verifierChargementXML() {
return (xml_charge);
} // fin verifierChargementXML()
</SCRIPT>
</HEAD>
<BODY>
JsLib 1.3
Exemple - xml.js
<NOSCRIPT>
Erreur : votre navigateur ne reconnait pas le Javascript ou est configuré pour ne
pas prendre en compte le code Javascript. Dans ce dernier cas, vous pouvez modifier la
configuration dans les préférences/options de votre navigateur.
</NOSCRIPT>
<P>Est-ce que votre navigateur prend en charge le XML ?
<SCRIPT TYPE="text/javascript" LANGUAGE="Javascript">
if (accepteXML()) document.write("oui");
else document.write("non");
</SCRIPT>
<FORM ACTION="GET" NAME="f1" onSubmit="return false">
<P>Charger le fichier "europe.xml" :
<INPUT TYPE=BUTTON NAME="b1" VALUE="Charger"
onClick="alert(chargerFichierXML("./extra/europe.xml"));">
<P>Vérifier le chargement du fichier "europe.xml" :
<INPUT TYPE=BUTTON NAME="b2" VALUE="Vérifier"
onClick="if (verifierChargementXML()) alert("Chargement des données OK.");
else alert("Chargement des données incomplet.");">
<P>Commentaires du document XML :
<INPUT TYPE=BUTTON NAME="b3" VALUE="Afficher"
onClick="alert(obtenirCommentaires());">
<P>Nom du noeud racine du document XML :
<INPUT TYPE=BUTTON NAME="b4" VALUE="Afficher"
onClick="alert(obtenirNomNoeud(obtenirNoeudRacine()));">
<P>Valeur du premier noeud de nom "etat" :
<INPUT TYPE=BUTTON NAME="b5" VALUE="Afficher"
onClick="alert(obtenirValeurNoeud(obtenirNoeud("etat")));">
<P>Valeur du premier noeud de nom "etat" fils du noeud racine du document XML :
<INPUT TYPE=BUTTON NAME="b6" VALUE="Afficher"
onClick="alert(obtenirValeurNoeud(obtenirNoeudFils(obtenirNoeudRacine(), "etat")));">
<P>Nom du noeud père du premier noeud de nom "etat" :
<INPUT TYPE=BUTTON NAME="b7" VALUE="Afficher"
onClick="alert(obtenirNomNoeud(obtenirNoeudPere(obtenirNoeud("etat"))));">
<P>Compter le nombre de noeuds de nom "etat" :
<INPUT TYPE=BUTTON NAME="b8" VALUE="Compter"
onClick="alert(compterNoeuds("etat"));">
<P>Rechercher l"année d"entrée dans l"Union d"un Etat européen
en fonction de son nom :
Etat : |
<INPUT TYPE=TEXT NAME="t1" VALUE="Allemagne" SIZE=40 MAXLENGTH=40> |
<INPUT TYPE=BUTTON NAME="b9" VALUE="Rechercher"
onClick="document.f1.t2.value=obtenirValeurAttribut(rechercherNoeud("etat", document.f1.t1.value), "entree");">
|
Entrée dans l"Union : |
<INPUT TYPE=TEXT NAME="t2" VALUE="" SIZE=4> |
|
<P>Rechercher un Etat européen en fonction de sa capitale :
Capitale : |
<INPUT TYPE=TEXT NAME="t3" VALUE="Riga" SIZE=40 MAXLENGTH=40> |
<INPUT TYPE=BUTTON NAME="b10" VALUE="Rechercher"
onClick="document.f1.t4.value=obtenirValeurNoeud(rechercherNoeudParAttribut("etat", "capitale", document.f1.t3.value));">
|
Etat : |
<INPUT TYPE=TEXT NAME="t4" VALUE="" SIZE=40> |
|
</FORM>
</BODY>
</HTML>
</source>
XML to JavaScript
<source lang="html4strict">
// convert XML data into JavaScript array of JavaScript objects
function XML2JS(xmlDoc, containerTag) {
var output = new Array();
var rawData = xmlDoc.getElementsByTagName(containerTag)[0];
var i, j, oneRecord, oneObject;
for (i = 0; i < rawData.childNodes.length; i++) {
if (rawData.childNodes[i].nodeType == 1) {
oneRecord = rawData.childNodes[i];
oneObject = output[output.length] = new Object();
for (j = 0; j < oneRecord.childNodes.length; j++) {
if (oneRecord.childNodes[j].nodeType == 1) {
oneObject[oneRecord.childNodes[j].tagName] =
oneRecord.childNodes[j].firstChild.nodeValue;
}
}
}
}
return output;
}
</source>