<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Playlist Generator</title>
<style>
textarea {
width: 100%;
height: 150px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2>XML Parsing to Display Playlist</h2>
<textarea id="input">
<songs>
<song rating="4.5">
<name>Hum thu hi</name>
<artist>Arijit</artist>
<movie>Aashiqui 2</movie>
</song>
<song rating="4.0">
<name>Thu hi mera</name>
<artist>Sunidhi Chauhan</artist>
<movie>Special 26</movie>
</song>
</songs>
</textarea>
<br>
<button id="genform">Generate Playlist</button>
<div id="playlist"></div>
<script>
document.getElementById('genform').addEventListener('click', function() {
// Get the XML from the textarea
const xmlText = document.getElementById('input').value;
// Parse the XML string
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
// Get all the song elements
const songs = xmlDoc.getElementsByTagName('song');
// Start building the HTML for the table
let table = '<table><tr><th>Title</th><th>Artist</th><th>Movie</th><th>Rating</th></tr>';
// Loop through the songs and extract the information
for (let i = 0; i < songs.length; i++) {
const name = songs[i].getElementsByTagName('name')[0].textContent;
const artist = songs[i].getElementsByTagName('artist')[0].textContent;
const movie = songs[i].getElementsByTagName('movie')[0].textContent;
const rating = songs[i].getAttribute('rating');
table += `<tr><td>${name}</td><td>${artist}</td><td>${movie}</td><td>${rating}</td></tr>`;
}
// Close the table HTML
table += '</table>';
// Insert the table into the playlist div
document.getElementById('playlist').innerHTML = table;
});
</script>
</body>
</html>
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter