Showing XML content with JavaScript

Trying to parse a simple XML list using JavaScript, but having trouble formatting it the way I need.

<TOURS>
<MONTH>
    <TOUR>
        <NUMBER>1</NUMBER>
        <VENUE>City Name - Venue Name</VENUE>
        <OTHER>Other stuff here</OTHER>
    </TOUR>
    <TOUR>
        <NUMBER>2</NUMBER>
        <VENUE>City Name - Venue Name</VENUE>
        <OTHER>Other stuff here</OTHER>
    </TOUR>
    <TOUR>
        <NUMBER>3</NUMBER>
        <VENUE>City Name - Venue Name</VENUE>
        <OTHER>Other stuff here</OTHER>
    </TOUR>
</MONTH>

<MONTH>
    <TOUR>
        <NUMBER>1</NUMBER>
        <VENUE>City Name - Venue Name</VENUE>
        <OTHER>Other stuff here</OTHER>
    </TOUR>
    <TOUR>
        <NUMBER>2</NUMBER>
        <VENUE>City Name - Venue Name</VENUE>
        <OTHER>Other stuff here</OTHER>
    </TOUR>
    <TOUR>
        <NUMBER>3</NUMBER>
        <VENUE>City Name - Venue Name</VENUE>
        <OTHER>Other stuff here</OTHER>
    </TOUR>
</MONTH>

Wanting to display two separate lists based on different months, but current code results in one large list of tours without separation based on months.

// Execute function when DOM is fully loaded 
$(document).ready(function(){ 

// Access the students.xml file
$.get("xml/tourinfo.xml",{},function(xml){

    // Create an HTML string
    myHTMLOutput = '';
    myHTMLOutput += '<div id="tours-container">';
    myHTMLOutput += '<img src="img/sep.png" style="vertical-align: middle;"></img>';

    // Iterate through each student tag in the XML file
    $('TOUR',xml).each(function(i) {
        
        tourNumber = $(this).find("NUMBER").text();
        tourVenue = $(this).find("VENUE").text();
        tourOther = $(this).find("OTHER").text();

        // Build row HTML data and store in string
        mydata = BuildStudentHTML(tourNumber,tourVenue,tourOther);
        myHTMLOutput = myHTMLOutput + mydata;

    });
    myHTMLOutput += '</div>';

    // Update the DIV called Content Area with the HTML string
    $("#tourData").append(myHTMLOutput);
});
});


function BuildStudentHTML(tourNumber,tourVenue,tourOther){

output = '';
output += '<ul id="tour-info-container">';
output += '<li id="tourNumber">'+ tourNumber + '</li>';
output += '<img src="img/sep.png" style="vertical-align: middle;"></img>';
output += '<li id="tourVenue">'+ tourVenue +'</li>';
output += '<img src="img/sep.png" style="vertical-align: middle;"></img>';
output += '<li id="tourOther">'+ tourOther +'</li>';
output += '</ul>';
return output;
}

Answer №1

To achieve the desired outcome, it is essential to iterate through each month and within that loop iterate over each "tour". Also, make sure to use the "var" keyword for declaring variables inside loops to avoid any potential issues. Currently, you are creating a new 'ul' element for every "TOUR", which leads to repeating IDs. Remember that IDs must be unique on a page, so consider changing them to classes instead.

Here's an updated solution that aligns more with your requirements:

// Function starts when DOM is fully loaded
$(document).ready(function() {

    // Load the students.xml file
    $.get("xml/tourinfo.xml", {}, function(xml) {

        // Initialize HTML output string
        var myHTMLOutput = '';
        myHTMLOutput += '<div id="tours-container">';
        myHTMLOutput += '<img src="img/sep.png" style="vertical-align: middle;"></img>';

        $('MONTH', xml).each(function(mIdx) {
            myHTMLOutput += '<ul class="tour-info-container">';
            
            // Iterate over each student tag in the XML file
            $('TOUR', xml).each(function(i) {
                var tourNumber = $(this).find("NUMBER").text();
                var tourVenue = $(this).find("VENUE").text();
                var tourOther = $(this).find("OTHER").text();

                // Create row HTML data
                var mydata = BuildStudentHTML(tourNumber, tourVenue, tourOther);
                myHTMLOutput += mydata;
            });
            myHTMLOutput += '</ul>';
        });
        myHTMLOutput += '</div>';
        $("#tourData").append(myHTMLOutput);
    });
});


function BuildStudentHTML(tourNumber, tourVenue, tourOther) {

    // Generate and return HTML string
    output = '';
    output += '<li class="tourNumber">' + tourNumber + '</li>';
    output += '<img src="img/sep.png" style="vertical-align: middle;"></img>';
    output += '<li class="tourVenue">' + tourVenue + '</li>';
    output += '<img src="img/sep.png" style="vertical-align: middle;"></img>';
    output += '<li class="tourOther">' + tourOther + '</li>';
    return output;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up JW Player with a YouTube Embed URL

Embed link Is it possible to embed a YouTube link in my JW Player without disrupting the design? I have a specific design for the JW Player frame that I need to retain while incorporating the YouTube link. I have searched extensively but haven't foun ...

Spin picture and optimize margins

I need help rotating an image by 90 degrees that is positioned between two boxes. The issue I am facing is that the rotated picture overlaps with the two boxes in this scenario. Example 1: Incorrect formatting CSS: .box{ height:50px; width:200px ...

Unable to locate CSS file in subfolder

Comparing two scenarios: Scenario 1 is problem-free, but issues persist in scenario 2. Review the details below: Scenario 1: MasterPages: Main\MasterPages.master Css : Main\Theme\CSS\ Javascript : Main\Theme\Javascrip ...

Vuetify's v-badge showcasing an exceptionally large number in style

Encountering an issue with using v-badge and v-tab when dealing with large numbers in a v-badge. Managed to find a CSS workaround by setting width: auto; for adjusting the size of v-badge to accommodate huge numbers, but now facing an overlap with my v-ta ...

Drag Bootstrap panels to the edge of the column

I need to position two panels in a column, with one on the left and the other on the right. Currently, they are not aligned properly, as shown in this image: https://i.stack.imgur.com/RU636.png The first panel should be moved to the left to align with the ...

iterate through the ordered list (ol) elements within nested lists

I am currently attempting to convert my hierarchical list into a JSON object in the following format; [ {title: title1,id: 1,children: [ {title: title1_1,id: 1_1,children: [ {title: title1_1_1,id: 1_1_1,children: []}, ...

Mongoose: efficiently fetching the query response

How are you doing? I'm just starting to learn about mongoose and mongoDB, and I'm encountering some issues with a basic query. Here is the code snippet in question: function addVoterToElection(req, res) { let query = Election.findOne({ &apos ...

The redundant element is continuously added to the fresh array

let index = 0; function generateList() { let list = ""; let v = 0; $.each(videoarr, function (i, value) { let name = videoarr[v].name; let img = videoarr[v].img; list += "<div id='video'><a href='#'><img ...

Tips on positioning a dropdown item to the far right of the page

I need help moving the language switcher and its items to the right side of the page. I tried using ml-auto but it didn't work for me. Whenever I try to adjust the position with padding-left, all the items end up in the center of the page. Any suggest ...

The dynamic styles set by CSS/JavaScript are not being successfully implemented once the Ajax data is retrieved

I am currently coding in Zend Framework and facing an issue with the code provided below. Any suggestions for a solution would be appreciated. The following is my controller function that is being triggered via AJAX: public function fnshowinfoAction() { ...

What is the best way to reference an Angular constant within a Gulp configuration file?

Is it possible to retrieve an Angular constant within a Gulp file? For example: angular.module('app').constant('env', { url: 'http://localhost:1337/' }); What is the method for accessing this constant inside a function ...

Exploring Ajax independently in Rails without the use of helper functions

Can Ajax post requests be made in Rails without using remote helpers? I am attempting to achieve this with the following code (including the coffeescript below). However, when I try to submit the form, I encounter an ActionController::UnknownFormat error ...

Apply CodeMirror theme and plugins using an HTML attribute

On my website, I have implemented a CodeMirror text area from . <form><textarea id="code" name="code" codemirror-type='lineNumbers: false, styleActiveLine: true, matchBrackets: true;'>CODE HERE</textarea></form> I added ...

Acquiring data within a jade template in order to generate static HTML pages

I am struggling to pass data to a jade template in order to generate static content. While I am not well-versed in node.js and express, I use jade as a template engine for creating static html. Many of the requests in the jade issue list pertain to includ ...

Vanilla JS method for resetting Bootstrap 5 client-side validation when focused

I'm currently exploring Bootstrap 5's client-side validation feature. However, I've encountered a usability issue with the is-invalid class. After clicking the submit button, this class persists until the correct input is entered. I would li ...

Link that updates periodically linked to an image

My goal is to have a URL change on a timer that is linked to an image. For example, after 10 seconds, I want the URL attached to the image to change without changing the actual image itself. I've been trying to figure out how to modify this code, but ...

developing a custom modal using a button in a React project with Material UI

Hello everyone, I have a question regarding React. I am fairly new to React and need some assistance with adding a new function that creates a Modal. I want to call this function onClick when the add icon is pressed (line 43). Any help would be appreciated ...

3D Object Anchored in Environment - Three.js

In my current scene, I have two objects at play. Utilizing the LeapTrackballControls library for camera movement creates a dynamic where one object appears to rotate based on hand movements. However, an issue arises as the second object also moves along w ...

Implementing customized line breaks in PHP using custom fields

My knowledge of PHP is quite limited, so I prefer to seek advice from experts before attempting anything I find online. I recently installed a customized billing field plugin in order to collect additional billing information during the checkout process. ...

Menu with option to delete next to each selection item

My task is to create a drop-down menu with a delete 'X' option next to each item. This functionality should work even when the drop-down is dynamically populated, without resorting to using a list as an alternative. UPDATE: The icons next to eac ...