Inspired? No home

How to loop through a XML document using the XML Parser (DOM Document)

XML/DOM/Parser 101:

This post will explain how to load a XML document and then loop through all elements and display the value. It will give you a brief introduction in how to use the DOMCDocument object in Microsoft XML Parser and how the DOM works.

XML looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<Users>
	<User>Espen</User>
	<User>Bill</User>
	<User>Steve</User>
</Users>

 

I have used a simple XML with one root element and three child nodes, each with their own node text. The DOM represent the XML like this:

Users (documentElement)

User (childNode 0) - Espen (childNode 0 nodeText)

User (childNode 1) - Bill (childNode 0 nodeText)

User (childNode 2) - Steve (childNode 0 nodeText) </em>

 

The is made up of node elements like shown above. These elements can have child and/or parent elements, attributes and a node text. We can use the DOM in JavaScript to retrieve and manipulate these elements. See the DOM specification for more information.

Below is the javascript code. It requires this XML Parser sniffer!

 

<script type="text/javascript" src="msxml_sniffer.js"></script>

<script type="text/javascript">
// requires XML Parser sniffer
var formValues_DOM = NewXMLParser('DOMDocument');
var formValues;

function getData() {
	var url;
	url = 'users.xml';
	if(typeof FormValues_DOM != 'object') {
		if(formValues_DOM > '') {
			formValues_DOM = new ActiveXObject(formValues_DOM)
		} else {
			alert('XML Parser not installed');
		}
	}
	formValues_DOM.async = false;
	formValues_DOM.load(url);
	if(formValues_DOM.parseError == 0) {
		formValues = formValues_DOM.documentElement;
	insertValues();
	}
	else {
		alert('XML not loaded');
	}
}

function insertValues() {
	var nodeValue;
	for(var i=0;i < formValues.childNodes.length;i++) {
		nodeValue= formValues.childNodes[i].text;
		// do something with the value here:
		alert(nodeValue);
	}
}
</script>
Written on 06 November 2004.
blog comments powered by Disqus