Skip to main content

XML DOM Loading and Parsing

W3C uses an abstract language called the Interface Definition Language (IDL).

The advantage of using IDL is that the developer learns to use the DOM with their preferred language and can easily switch to a different language.

The disadvantage is that, since it is abstract, the IDL cannot be used directly by Web developers.

Parser

A parser is a software application that is designed to analyze a document (in our case an XML document) and do something with the information.

Some examples of DOM parser are:

  • JAXP: Sun Microsystem’s Java API for XML Parsing (JAXP)
  • XML4J: IBM’s XML Parser for Java (XML4J)
  • msxml: Microsoft’s XML parser (msxml) version 2.0 is built-into Internet Explorer 5.5
  • 4DOM: 4DOM is a parser for the Python programming language
  • XML::DOM: XML::DOM is a Perl module to manipulate XML documents using Perl
  • Xerces: Apache’s Xerces Java Parser
note

In a tree-based API like DOM, the parser traverses the XML file and creates the corresponding DOM objects. Then you can traverse the DOM structure back and forth.

Loading and Parsing XML

While loading an XML document, the XML content can come in two forms:

  • Directly as XML file
  • As XML string

Content as XML file

//if browser supports XMLHttpRequest
if (window.XMLHttpRequest) {
// Create an instance of XMLHttpRequest object. code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

// sets and sends the request for calling "node.xml"
xmlhttp.open("GET","/dom/node.xml",false);
xmlhttp.send();

// sets and returns the content as XML DOM
xmlDoc = xmlhttp.responseXML;

Content as XML string

// loads the xml string in a dom object  
function loadXMLString(t) { // for non IE browsers
if (window.DOMParser) { // create an instance for xml dom object
parser = new DOMParser();
xmlDoc = parser.parseFromString(t,"text/xml");
} else { // code for IE
// create an instance for xml dom object
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false; xmlDoc.loadXML(t);
}
return xmlDoc;
}


// a variable with the string
var text = "<Employee>";
text = text+"<FirstName>Tanmay</FirstName>";
text = text+"<LastName>Patil</LastName>";
text = text+"<ContactNo>1234567890</ContactNo>";
text = text+"<Email>[email protected]</Email>";
text = text+"</Employee>";

// calls the loadXMLString() with "text" function and store the xml dom in a variable
var xmlDoc = loadXMLString(text); //parsing the DOM object
y = xmlDoc.documentElement.childNodes;
for (i = 0;i<y.length;i++) {
document.write(y[i].childNodes[0].nodeValue);
document.write("<br>");
}