JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript XML File


AJAX allows web pages to dynamically load and process data from the server without reloading. One common format for server responses is XML (eXtensible Markup Language).

Although JSON is more widely used today, understanding XML is important for working with older systems or APIs that still use it.

What Is an XML File?

XML is a structured format for storing data. It uses tags to define elements and their content, similar to HTML.

Example data.xml:

<users>
  <user>
    <name>Vicky</name>
    <age>28</age>
    <email>vicky@example.com</email>
  </user>
  <user>
    <name>Sanjana</name>
    <age>25</age>
    <email>sanjana@example.com</email>
  </user>
</users>

In this example:

  • <users> is the parent element.

  • Each <user> contains <name>, <age>, and <email> tags.

Fetching an XML File Using AJAX

To load an XML file, use the XMLHttpRequest object.

let xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);

xhr.onload = function() {
  if (xhr.status === 200) {
    let xml = xhr.responseXML; // Parse the XML file
    console.log(xml);
  } else {
    console.error("Error loading XML file:", xhr.status);
  }
};

xhr.send();

Explanation:

  • xhr.responseXML automatically parses the XML into a DOM object.

  • You can now access nodes using standard DOM methods like getElementsByTagName().

Accessing XML Nodes

Once the XML is loaded, you can traverse and extract data.

let users = xml.getElementsByTagName("user"); // Get all <user> elements

for (let i = 0; i < users.length; i++) {
  let name = users[i].getElementsByTagName("name")[0].textContent;
  let age = users[i].getElementsByTagName("age")[0].textContent;
  let email = users[i].getElementsByTagName("email")[0].textContent;

  console.log(`Name: ${name}, Age: ${age}, Email: ${email}`);
}

Explanation:

  • getElementsByTagName("user") returns a NodeList of all <user> elements.

  • [0] selects the first child of the node.

  • textContent extracts the text inside the tag.

Displaying XML Data on a Web Page

You can dynamically insert XML data into the HTML using JavaScript.

<div id="output"></div>
<button id="loadBtn">Load Users</button>

<script>
document.getElementById("loadBtn").addEventListener("click", function() {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "data.xml", true);

  xhr.onload = function() {
    if (xhr.status === 200) {
      let xml = xhr.responseXML;
      let users = xml.getElementsByTagName("user");
      let html = "";

      for (let i = 0; i < users.length; i++) {
        let name = users[i].getElementsByTagName("name")[0].textContent;
        let age = users[i].getElementsByTagName("age")[0].textContent;
        let email = users[i].getElementsByTagName("email")[0].textContent;

        html += `<p>Name: ${name}, Age: ${age}, Email: ${email}</p>`;
      }

      document.getElementById("output").innerHTML = html;
    } else {
      document.getElementById("output").textContent = "Failed to load XML";
    }
  };

  xhr.send();
});
</script>

Explanation:

  • Each <user> is looped over to extract details.

  • The information is displayed in the <div> dynamically without page reload.

Handling Nested XML

XML files can be nested with multiple levels of tags. You can use getElementsByTagName() repeatedly to reach nested elements.

Example:

<company>
  <department>
    <name>IT</name>
    <employee>
      <name>Vicky</name>
      <role>Developer</role>
    </employee>
    <employee>
      <name>Sanjana</name>
      <role>Designer</role>
    </employee>
  </department>
</company>

JavaScript:

let departments = xml.getElementsByTagName("department");
for (let i = 0; i < departments.length; i++) {
  let deptName = departments[i].getElementsByTagName("name")[0].textContent;
  let employees = departments[i].getElementsByTagName("employee");

  for (let j = 0; j < employees.length; j++) {
    let empName = employees[j].getElementsByTagName("name")[0].textContent;
    let role = employees[j].getElementsByTagName("role")[0].textContent;
    console.log(`${deptName} - ${empName} (${role})`);
  }
}

Error Handling

Always check the status property to handle errors:

xhr.onload = function() {
  if (xhr.status === 200) {
    console.log("XML Loaded Successfully");
  } else if (xhr.status === 404) {
    console.error("XML file not found");
  } else {
    console.error("Server error:", xhr.status);
  }
};

This ensures your app doesn’t break if the file is missing or the server fails.

Combining AJAX XML with HTML Forms

You can also use XML responses to populate form elements dynamically.

Example: populating a <select> with user names from XML:

let select = document.getElementById("userSelect");
let users = xml.getElementsByTagName("user");

for (let i = 0; i < users.length; i++) {
  let name = users[i].getElementsByTagName("name")[0].textContent;
  let option = document.createElement("option");
  option.value = name;
  option.textContent = name;
  select.appendChild(option);
}

This makes web pages more interactive and data-driven.

Summary of the Tutorial

AJAX with XML files allows you to:

  • Load structured XML data without reloading the page.

  • Access nested tags using getElementsByTagName().

  • Display data dynamically on the page.

  • Handle errors using HTTP status codes.

  • Integrate XML responses into forms and other UI elements.

While JSON is more common today, working with XML is still useful for legacy systems or APIs that rely on XML. Mastering XML responses gives you the foundation to handle any type of AJAX data.


Practice Questions

  1. Write an AJAX request to fetch data.xml and display all <user> names in a <div> when a button is clicked.

  2. Fetch data.xml and display each user’s name, age, and email dynamically in separate <p> elements.

  3. Write code to loop through nested XML tags, such as <department> and <employee>, and log employee names with their department.

  4. Create an AJAX request that checks for errors (404 or 500) while fetching data.xml and displays an alert if the file is missing.

  5. Use responseXML to fetch XML data and populate a <select> dropdown with user names.

  6. Fetch an XML file and display only the users whose age is greater than 25 in a list.

  7. Create a button that loads an XML file and appends each user’s information to an existing <div> without replacing previous content.

  8. Write a function that fetches XML data and converts it into JSON format using JavaScript.

  9. Use AJAX to fetch an XML file and filter users by a specific tag value, then display the filtered results dynamically.

  10. Write code to fetch an XML file and log both the tag names and their text content for all child elements of <user>.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top