XML

Contact Us or call 1-877-932-8228
XML

XML

In addition to the responseText property, XMLHttpRequest objects also have a responseXML property, which holds the data returned from the server as an XML document object (or null if the body content returned is not well-formed XML).

The properties and methods for accessing and inserting nodes into HTML documents also apply to XML documents. They are shown below:

Properties for Accessing Element Nodes
Property Description
documentElement The root element of the document (applicable to the document object, not to the descendant nodes).
childNodes[] A nodeList containing all of a node's child nodes.
firstChild A reference to a node's first child node. Same as childNodes[0].
lastChild A reference to a node's last child node. Same as childNodes[childNodes.length-1].
nextSibling A reference to the next node at the same level in the document tree.
parentNode A reference to a node's parent node.
previousSibling A reference to the previous node at the same level in the document tree.
Methods for Inserting Nodes
Method Description
appendChild() Takes a single parameter: the node to insert, and inserts that node after the last child node.
insertBefore() Takes two parameters: the node to insert and the child node that it should precede. The new child node is inserted before the referenced child node.
replaceChild() Takes two parameters: the new node and the node to be replaced. It replaces the old node with the new node and returns the old node.
setAttribute() Takes two parameters: the attribute name and value. If the attribute already exists, it replaces it with the new value. If it doesn't exist, it creates it.

The demo below shows how to load an XML document, to read parts of it into a string and then output that string as HTML to a part of the page.

To run the demo, first:

  1. From the command line (on a PC) or terminal (on a Mac), navigate to the directory PassingData/Demos/.
  2. Type npm install to load the required Node.js modules.
  3. Type npm start to start the server.
  4. Open http://localhost:8080/XML.html in a browser.

Code Sample:

PassingData/Demos/XML.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>XML</title>
<link href="xml.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="lib.js"></script>
<script type="text/javascript">
	function init() {
		var btnLoad = document.getElementById("btnLoad");
		observeEvent(btnLoad, "click", loadXml);
	}

	function loadXml() {
		var btnDisplay = document.getElementById("btnDisplay");
		var output = document.getElementById("output");
		var xmlhttp = new XMLHttpRequest();
		var xmlDoc;

		xmlhttp.open("GET", "Beatles.xml", true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				output.innerHTML = "XML Loaded";
				xmlDoc = xmlhttp.responseXML;
			}
		}
		xmlhttp.send(null);

		observeEvent(btnDisplay, "click", function() {
			var btnClear = document.getElementById("btnClear");
			addNodes(xmlDoc.documentElement);
			observeEvent(btnClear, "click", clearXml);
		});
	}

	function addNodes(node, parent) {
		var output = document.getElementById("output");
		var child, cls;
		var list, listitem, sublist;

		if (!parent) {
			output.innerHTML = "";
			list = document.createElement("ol");
			output.appendChild(list);
		} else {
			list = parent;
		}

		for (var i = 0; i < node.childNodes.length; i++) {
			child = node.childNodes[i];
			cls = (child.nodeType == 3) ? "textnode" : "nontextnode";

			listitem = document.createElement("li");
			listitem.className = cls;
			listitem.innerHTML = child.nodeName + ": " + child.nodeValue;
			list.appendChild(listitem);

			if (child.hasChildNodes()) {
				sublist = document.createElement("ol");
				listitem.appendChild(sublist);
				addNodes(child, sublist);
			}
		}

		if (node.nodeType == 1) { //Element Node
			for (var i = 0; i < node.attributes.length; i++) {
				listitem = document.createElement("li");
				listitem.className = "attribute";
				listitem.innerHTML = node.attributes[i].nodeName + ": " + node.attributes[i].nodeValue;
				list.appendChild(listitem);
			}
		}
	}

	function clearXml() {
		document.getElementById("output").innerHTML = "XML Cleared";
	}

	observeEvent(window, "load", init);
</script>
</head>
<body>
	<button id="btnLoad">Load XML</button>
	<button id="btnDisplay">Display XML</button>
	<button id="btnClear">Clear XML</button>
	<div id="output"></div>
</body>
</html>
  1. The page loads and shows three buttons: "Load XML", "Display XML", and "Clear XML".
  2. Clicking the "Load XML" button, the request for the XML document is made and the XML document is returned as the screenshot below shows: XML Document Returned Notice that the XML has not yet been incorporated into the page, but you can see in Firebug at the bottom of the browser that the XML has indeed been returned.
  3. Clicking the "Display XML" button builds an HTML list node by node: HTML List Node by Node
  4. Clicking the "Clear XML" button changes the innerHTML property of the output div to an empty string, thereby removing the list from the page. This does not remove the XML document from memory. You can see this by clicking on the "Load XML" button again.

Creating an addChild() Function

Adding nodes to the DOM can be a lot of work. It can involve several steps, including:

  1. Creating a new element node.
  2. Appending the element node as a child of another element.
  3. Creating a new text node.
  4. Appending the text node to the new element node.
  5. Adding one or more attributes with the setAttribute() method of the new element.

The user-defined function below (included in our lib.js file) makes this process easier.

function addChild(doc, parent, child, childText, attributes) { if (typeof child == "string") { childNode = doc.createElement(child); } else { childNode = child; } if (typeof childText == "string") { childTextNode = doc.createTextNode(childText); childNode.appendChild(childTextNode); } if (attributes) { for (var att in attributes) { childNode.setAttribute(att,attributes[att]); } } parent.appendChild(childNode); return childNode; }

This addChild() function requires the first three parameters: the DOM document, parent-to-be node, and child-to-be (either an existing node or the name of the node-to-be). The function can also take the text that will become the contents of the new child and an attributes object for the new child. The demo below shows how the function is called:

Code Sample:

PassingData/Demos/addChild.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="lib.js"></script>
<script type="text/javascript">
	observeEvent(window, "load", function() {
		var atts = {
			"style": "background:red;color:white;",
			"align": "center"
		}
		addChild(document, document.getElementsByTagName("body")[0], "p", "Hello World!", atts);
	});
</script>
<title>Add Child Demo</title>
</head>
<body>
<h1>Add Child Demo</h1>
</body>
</html>
Next