Extensible Markup Language (XML)

CSE 190 M (Web Programming), Spring 2007

University of Washington

Reading: Sebesta Ch. 8 sections 8.1 - 8.3, 8.7 - 8.8, 8.10.3

Valid XHTML 1.0 Strict Valid CSS!

What is XML?

Structure of an XML document

An example XML file

<?xml version="1.0" encoding="UTF-8"?>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <subject>Reminder</subject>
    <message>
        Don't forget me this weekend!
    </message>
</note>

Larger XML file example

<?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="computers">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <year>2003</year><price>49.99</price>
</book>
<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year><price>29.99</price>
</book>
<book category="computers">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year><price>39.95</price>
</book></bookstore>

Resulting tree structure (partial)

node tree

What tags are legal in XML?

Facts about XML data

Displaying XML data on a web page

Ajax XMLHttpRequest template for XML

var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
    if (ajax.readyState == 4) {
        do something with ajax.responseXML;
    }
};
ajax.open("GET", url, true);
ajax.send(null);

DOM node properties/methods

Details about XML node properties

Navigating the node tree

element.getElementsByTagName("tag")
element.getAttribute("attributeName")

Recall: XML file

<?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="computers">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <year>2003</year><price>49.99</price>
</book>
...
</bookstore>

Navigating node tree example

var xmlDoc = ajax.responseXML;
var books = xmlDoc.getElementsByTagName("book");
for (var i = 0; i < books.length; i++) {
    var category = books[i].getAttribute("category");
    if (category == "computers") {
        var title = books[i].getElementsByTagName("title")[0].nodeValue;
        var author = books[i].getElementsByTagName("author")[0].nodeValue;
    
        var p = document.createElement("p");
        p.innerHTML = title + ", by " + author;
        document.body.appendChild(p);
    }
}

Practice problem: Animal game