XML DOM


DOM stands for Document Object Model. To best understand what the DOM is, we will briefly discuss the HTML DOM first. When a web page is loaded, the browser creates a Document Object Model of the page. The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a standard for accessing documents: “The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.”

In other words, the HTML DOM is a standard for how to get, change, add, or delete HTML elements. It provides full CRUD ability. (Create, Read, Update and Delete). With the object model, JavaScript gets all the power it needs to create dynamic HTML.

All XML elements can be accessed through the XML DOM. Consider the following XML document.

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
</bookstore>

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<script>
var parser, xmlDoc;
var text = "<bookstore>" + 
"<book>" +
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book>" +
"<book>" +
"<title>Special Occasion Italian</title>" +
"<author>Joe Blow</author>" +
"<year>2006</year>" +
"</book>" +
"</bookstore>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");

document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
document.getElementById("demo2").innerHTML =
xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue;
document.getElementById("demo3").innerHTML =
xmlDoc.getElementsByTagName("title")[1].childNodes[0].nodeValue;
document.getElementById("demo4").innerHTML =
xmlDoc.getElementsByTagName("author")[1].childNodes[0].nodeValue;
</script>
</body>
</html>

Here is the output, courtesy of w3schools.com. I modified their code, by the way.

Series Navigation<< XML TreeXML and XPath >>

Leave a comment

Your email address will not be published. Required fields are marked *