- 2072 Asoj · 2+8 marks
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
- Data in XML. The server holds or sends data as XML.
- Fetch the XML. JavaScript requests it using
XMLHttpRequest(AJAX) or loads a file. - Parse. The browser builds an XML DOM tree from the response (
responseXMLorDOMParser). - Process. JavaScript walks the tree with
getElementsByTagName, reads values and does calculations or filtering. - 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)
Related questions
- AJAX features; CGI, Perl, JavaScript helpers · Internet and Intranet, chapter 6
- Web-mail to POP3 message transfer protocols · Internet and Intranet, chapter 3
- Server-side programming and Java Servlet · Web Technology, chapter 3
- How the Internet and Web work together · Web Technology, chapter 1
- Client-side versus server-side scripting · Web Technology, chapter 3 · asked 3×
- XML and its significance in the Web · Web Technology, chapter 7