Skip to main content

XML and JavaScript for client-side web apps

Short answer

JavaScript fetches XML data asynchronously with XMLHttpRequest, parses it into an XML DOM, then reads nodes and updates the HTML DOM to display content without a page reload. XML carries structured data while JavaScript manipulates it client-side; JSON is a common alternative.

How are XML and JAVA SCRIPTS used together to develop client-side web applications?

XML (eXtensible Markup Language) stores and carries data in a structured, self-describing way. JavaScript runs in the browser and can read and change a web page. Together they allow a page to get data, process it and show it on the client without a page reload.

How they are used together

  1. Data in XML. The server holds or sends data as XML.
  2. Fetch the XML. JavaScript requests it using XMLHttpRequest (AJAX) or loads a file.
  3. Parse. The browser builds an XML DOM tree from the response (responseXML or DOMParser).
  4. Process. JavaScript walks the tree with getElementsByTagName, reads values and does calculations or filtering.
  5. Display. JavaScript writes the result into the HTML DOM (innerHTML, creating table rows) or applies an XSLT style sheet.

Example

Data file books.xml:

<library>
  <book><title>Networks</title><price>450</price></book>
  <book><title>Internet</title><price>380</price></book>
</library>

HTML and JavaScript:

<div id="out"></div>
<script>
var x = new XMLHttpRequest();
x.onreadystatechange = function () {
  if (x.readyState == 4 && x.status == 200) {
    var books = x.responseXML.getElementsByTagName("book");
    var s = "";
    for (var i = 0; i < books.length; i++) {
      s += books[i].getElementsByTagName("title")[0].textContent +
           " - Rs " +
           books[i].getElementsByTagName("price")[0].textContent + "<br>";
    }
    document.getElementById("out").innerHTML = s;
  }
};
x.open("GET", "books.xml", true);
x.send();
</script>
 XML file/server --HTTP--> [JavaScript XHR] --> XML DOM
                                  |
                       read nodes, process
                                  |
                          update HTML DOM

Uses and advantages

  • Product lists, news feeds (RSS), form validation lists and menus loaded without reloading.
  • Sorting and filtering done on the client, reducing server load.
  • XML is platform independent and readable, so the same data can feed many applications.
  • XSLT can transform XML to HTML in the browser.
  • Today JSON is often used instead of XML, but the method is the same.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Internet and Intranet chapter 6 questions →