< JavaScript

Simple function to open an XML file

This function first tries for Microsoft Internet Explorer, then for Firefox and others:

function loadXMLDoc(xmlfilename) {
  var event = new Error();
  // Internet Explorer
  try {
    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  } catch(event) {
    // Firefox, Mozilla, Opera, others
      try {
      xmlDoc = document.implementation.createDocument("","",null);
    } catch(event) {
      throw(event.message);
    }
  }

  try {
    xmlDoc.async = false;

    xmlDoc.load(xmlfilename);
    return(xmlDoc);
  } catch(event) {
    throw(event.message);
  }
  return(null);
}

Usage

var objXML = loadXMLDoc("filename.xml");
var oNodes = objXML.getElementsByTagName("AnyTagYouWish");

Now you can do any DOM operations on oNodes.

XML modifications can't be saved in JavaScript, as this is clientside…

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.