Integrate XML information into a webpage's table layout

I am currently working on integrating an XML file into my HTML and displaying it in a table. A snippet of the XML is provided below:

<?xml version="1.0" encoding="UTF-8"?>
<product category="DSLR" sub-category="Camera Bundles">
    <id>0001</id>
    <title>Canon EOS Rebel T6 DSLR Camera Bundle with EF-S 18-55mm f/3.5-5.6 IS II Lens + Canon EF 75-300mm f/4-5.6 III Lens</title>
    <brand>Canon</brand>
    <price>399.99</price>
    <description>The Canon EOS Rebel T6 DSLR Camera Bundle allows you to capture stunning moments with exceptional quality. This compact camera features an 18-megapixel CMOS sensor, delivering sharp images even in low-light conditions. With an ISO range of 100 to 6400 (expandable to 12800), you can take clear and detailed photos in any lighting. The DIGIC 4+ image processor ensures fast performance and vibrant colors, making every photo memorable.</description>
</product>

Based on the ID, title, brand, price, and description tags, I have attempted to write jQuery code to link them to the table, but I am facing difficulties in making it work.

$(document).ready(function() {
  $.ajax({
    type: "GET",
    url: "productsXmlStructure.xml",
    dataType: "xml",
    success: function(xml){
      $('#t01').append('<th>ID</th>'); 
      $('#t01').append('<table id="show_table">'); 
      $(xml).find('show').each(function(){
        var $show = $(this);
        var id = $show.find('ID').text();
        var title = $show.find('Title').text();
        var brand = $show.find('Brand').text();
        var price = $show.find('Price').text();
        var desc = $show.find('Description').text();
      });
    }
  });
});

I have limited knowledge in this language, but I have included my table structure below. I would appreciate any assistance in identifying where I may be going wrong.

<table id="t01" border="2" style="width:75%" align="center">
  <tr>
    <th>ID</th>
    <th>Title</th>
    <th>Brand</th>
    <th>Price</th>
    <th>Description</th>
  </tr>
</table>

Answer №1

  1. Opt for using filter in place of find
  2. Choose product over show (as per the XML)
  3. Append a row to #t01 for each occurrence of product.
  4. Add a cell to the above row for each property with the corresponding data.

var xml = '<?xml version="1.0" encoding="UTF-8"?> <product top-level-category="DSLR" sub-level-category="Camera Bundles"> <id>0001</id> <title>NIKON D3300 DSLR Camera with 18-55 mm f/3.5-5.6 II ED Zoom Lens – BlacK</title> <brand>Nikon</brand> <price>279.00</price> <description>The Nikon D3300 DSLR Camera with 18-55 mm f/3.5-5.6 II ED Zoom Lens allows you to capture special moments in glorious high quality. Unforgettable memories, unforgettable photos. Small and lightweight, the D3300 has a 24.2 megapixel, 23.5 x 15.6 mm CMOS sensor with remarkable light sensitivity that produces amazingly sharp images. It performs well in low light with an ISO range of 100 to 12800 (extendable to 25600). Your images will be packed with fine textures and natural colours to really capture the atmosphere of whichever situation you find yourself in. Capture clear, colourful photographs in all manner of lighting conditions as the camera\'s EXPEED 4 image processor goes to work, delivering gorgeous photos every time.</description></product>';

$(xml).filter('product').each(function(){
  var $show = $(this);
  var data = {
    id: $show.find('ID').text(),
    title: $show.find('Title').text(),
    brand: $show.find('Brand').text(),
    price: $show.find('Price').text(),
    desc: $show.find('Description').text()
  };

  var row = $('<tr />');
  for (var prop in data) {
    $('<td>' + data[prop] + '</td>').appendTo(row);  
  }
  
  $('#t01').append(row);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="t01" table border="2" style="width:75%" table align="center">
  <tr>
    <th>ID</th>
    <th>Title</th>
    <th>Brand</th>
    <th>Price</th>
    <th>Description</th>
  </tr>
</table>

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

Issue with Angular custom tag displaying and running a function

I have created a custom HTML tag. In my next.component.ts file, I defined the following: @Component({ selector: 'nextbutton', template: ` <button (click) = "nextfunc()">Next</button> ` }) export class NextComponent{ nextfunc( ...

Transferring values from jQuery AJAX to Node.js

Is there a way to successfully pass a variable from jQuery to nodejs without getting the [object Object] response? I want to ensure that nodejs can return a string variable instead. $('.test').click(function(){ var tsId = "Hello World"; ...

How to Align Navigation Searchbar in Center When Bootstrap is Collapsed

I am attempting to center my search bar when it is collapsed. Currently, it appears like this: As you can see, the links are centered, but not the search bar. This is the existing HTML structure: <!-- Navigation Bar Start --> <div class ...

Guidelines for dynamically displaying <router-link> or <a> in Vue based on whether the link is internal or external

<template> <component :is="type === 'internal' ? 'router-link' : 'a'" :to="type === 'internal' ? link : null" :href="type !== 'internal' ? link : null" > <slot /> < ...

Optimal method for sending FQL response to cakephp controller using jQuery

My FQL result is a JavaScript object with the following structure: [{"name":"3904","fql_result_set":[{"like_count":"0"}]},{"name":"7617","fql_result_set":[{"like_count":"0"}]},{"name":"9674","fql_result_set":[{"like_count":"0"}]}] I am struggling to pass ...

Guide on submitting a reply to Harvard's "Guess my Word" challenge using JSoup

I am currently working on developing a bot to enhance my gameplay in Harvard's intriguing "Guess my Word!" game. After some exploration, I found out about a post request feature available through Chrome's "inspect element" functionality when a pl ...

Creating a table with adjustable row heights is a great way to enhance the user

Can the height of an HTML table row be adjusted dynamically by dragging and dropping, similar to how it's done in this demo (https://reactdatagrid.io/docs/row-resize), but for free? ...

Error 404 encountered while attempting to access dist/js/login in Node.JS bootstrap

I currently have a web application running on my local machine. Within an HTML file, I am referencing a script src as /node_modules/bootstrap/dist/js/bootstrap.js. I have configured a route in my Routes.js file to handle this request and serve the appropri ...

Despite being in perfect condition, my If-Else statement is refusing to function properly

I had previously posted a similar question, but it was removed. However, I am still very curious about why something seemingly trivial is not functioning properly. This is the entirety of my HTML and JavaScript code... <!doctype html> <html lang=& ...

Using Ajax to send data to a model within another model in ASP.NET Core MVC

I'm new to this platform and I'm curious about sending model data within another model from ajax to controller. Here are my models: public class mfItems { [Key] [Display(Name = "Item ID")] public string ItemID { get; set; } ...

Issues with Async Ajax functionality are being reported specifically in Safari browsers when a redirect

Encountering issues with an async Ajax call not functioning in Safari while working perfectly fine in other browsers. The problem arises when there is a redirect/link on the button or anchor that triggers the Ajax function. Here's a basic example: & ...

Arranging based on attribute data

I'm currently working on organizing a collection of divs that have unique custom data attributes which I aim to sort based on user selection. For instance, if 'followers' is chosen, the .box elements will be arranged according to their data- ...

Problem with BeautifulSoup table parsing

I've been trying to create a table with expenses, amounts, and actions, but I'm having trouble with the alignment. I attempted to adjust it by changing the width, but that didn't solve the issue. Can someone point out what I'm doing wro ...

RequestDispatcher.forward() does not work when servlet is invoked through an Ajax POST request

My login page involves user authentication through the firebase and sending the request to a servlet. When I click the submit button with correct credentials, the firebase authentication works, the servlet is called but an error is displayed in the browser ...

organizing data using backbone marionette router

I am attempting to display the query string, but I am only receiving null as output. The query string I am using is http:://localhost/admin/brands?foo=bar and no matter what I try, queryString remains null. I even attempted /brands/?foo=bar with no succes ...

Switching between fixed and unfixed divs causes two absolute divs to alternate

I am currently working on a code to keep a fixed div ("two") in place between two absolute positioned divs ("one" and "footer") while scrolling. However, there is an issue that arises when the browser window is resized. The distance between the footer and ...

Steps for Updating Jquery Mobile Listview Following an Ajax Request

I am currently facing an issue with refreshing the listview in Jquery Mobile after pulling Ajax content into a div. The problem specifically arises when the Ajax content is loaded into a listview within a collapsible content block. Below is the HTML snip ...

The sweetalert 2 input field is unresponsive or disabled within a materializecss modal, making it impossible to type in

My modal includes a SweetAlert2 popup when I click the "add bills" button. The code for this feature is from their documentation, so I don't believe the issue lies there. However, I am experiencing a problem where the input field is not type-able and ...

Generating a list of items to buy using a JSON document

So here's the json file I'm working with: [ {"task":"buy bread","who":"Sarah","dueDate":"2023-10-18","done":false}, {"task":"clean car","who":"David","dueDate":"2023-08-30","done":true}, {"task":"write report","who":"Jenny","dueDate":"2023-09 ...

Positioning two divs to the right of another div

I am facing an issue with aligning the menu and categories divs to the right of the logo div in the following example: jsfiddle. I want them to remain stacked one under another as they are currently, but I am unable to achieve the desired display. Any ass ...