Show values from an XML file using javascript

XML file using the JavaScript

  • We use XMLHttpRequest for the xml

XML File (inf.xml) :

<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user>
        <name>Pendyala Swetha</name>
        <email>[email protected]</email>
    </user>
    <user>
        <name>Penyala Navyasree</name>
        <email>[email protected]</email>
    </user>
</users>

 

HTML FILE :

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XML Data</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f9f9f9;
            padding: 20px;
        }
        .user {
            background-color: #4428a7; 
            color: #fff; 
            padding: 10px;
            margin: 10px ;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <h1>User Information</h1>
    <div id="users"></div>

    <script>
    
        function loadXMLDoc(filename) {
            return new Promise((resolve, reject) => {
                const xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (this.readyState == 4 && this.status == 100) {
                        resolve(this.responseXML);
                    } else if (this.readyState == 4) {
                        reject('Failed to load XML file');
                    }
                };
                xhttp.open("GET", filename, true);
                xhttp.send();
            });
        }


        function displayUsers(xml) {
            const users = xml.getElementsByTagName("user");
            const usersContainer = document.getElementById("users");

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

                const userDiv = document.createElement("div");
                userDiv.className = "user";
                userDiv.innerHTML = `<h2>${name}</h2><p>${email}</p>`;

                usersContainer.appendChild(userDiv);
            }
        }

        loadXMLDoc("inf.xml")
            .then(displayUsers)
            .catch(error => console.error(error));
    </script>
</body>
</html>

 

Leave a Comment

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

Scroll to Top