Dynamically assigning XML nodes and their content to variables: a step-by-step guide

My XML file is quite extensive, divided into various sections. Each page loads content from the XML based on a category node (list_node). Currently, I am extracting content by directly referencing the nodes, but it becomes cumbersome to add a line for each node.

Is there a way to parse the XML, store the nodes in an array, and then assign a new variable to represent the node name and its contents? This snippet shows my current configuration:

<media_item>
<title>temporary title</title>
<key>652843722</key>
<path>/states/CA</path>
<filename>climate-pollution-harmful.html</filename>
<link>http://a-url-goes-here.com</link>
<blank>yes</blank>
<author/>
<date>August&nbsp;15,&nbsp;2015</date>
</media_item>

(Please note that the actual XML contains more nodes than shown above, with different categories indicated by the "list_node" call earlier in my code)

 $.ajax({
        type: "GET",
        url: "http://url-of/file.xml,
        dataType: "xml",
        success: function(xml){             
            $(xml).find(list_node).each(function(i){
                var title = $(this).find('title').text();
                var url = $(this).find('link').text();
                var date = $(this).find('date').text();
                var author = $(this).find('author').text();
                var org = $(this).find('org').text();

Instead of manually defining variables like "var title = $(this).find('title').text();" for every node, I am looking for a way to automate this process.

Answer №1

If all the nodes consist of text only, you can iterate through children() and generate an array of objects using the tagName as property names

$.get('data.xml', function (xml) {

    var results = $(xml).find('media_item').map(function () {
        var row = {}
        $(this).children().each(function () {
            row[this.tagName] = $(this).text();
        });
        return row;
    }).get();

    console.log(results);

}, 'xml');

This method can be easily modified to include attributes as well.

The provided code transforms the XML into:

[
 {
  "title": "temporary title",
  "key": "652843722",
  "path": "/states/CA",
  "filename": "climate-pollution-harmful.html",
  "link": "http://a-url-goes-here.com",
  "blank": "yes",
  "author": "",
  "date": "August 15, 2015"
 }
]

DEMO

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

Counting selected files can be done by following these steps

My form includes a simple input field like so: <input id="my_id" multiple="true" type="file" name="image_name[]" /> I need help with the following questions: What is the best way to calculate the number of selected files using jQuery or pure Java ...

Accessing public static files in Express by using the routes folder

I'm currently facing an issue with accessing a static file named 'home.html' located in the public directory of my app's architecture: public home.html routes index.js views myapp.js In myapp.js: var express = require('ex ...

PHP-based user interface queue system

I am in the process of developing a website that enables users to manipulate a webcam by moving it from left to right. Each user will have a one-minute window to control the camera. I plan on implementing a queuing system on the site to ensure that users ...

Animating a progress bar with JQuery

Having issues with displaying a progress bar using jquery and javascript, as it is not appearing on the page. var show_time = Math.floor(Math.random() * 10000) + 5000; setTimeout(function() { $("#progress").hide() }, show_time); var myCountdown = $( ...

The presence of too many select options can result in a delay in text input responsiveness on an iPad

My HTML form is styled with CSS and functions properly. However, I encountered a delay issue when testing it on an iPad (both iOS7 and 8) - the native keyboard responds very slowly (around 1-2 seconds) to key presses when entering text into the form fields ...

Retrieve data from a particular XML document

I am trying to parse XML in Java. The XML structure is as follows: <Attributes><ProductAttribute ID="359"><ProductAttributeValue><Value>1150</Value></ProductAttributeValue></ProductAttribute><ProductAttribute I ...

The MUI Select event is coming back as undefined

I am facing an issue with a Select component in my MUI form. Here is my current state: const [formdata, setformdata] = useState({}); This is my event handler: const onchangehandle = (e) => { setformdata((prevState) => ({ ...prevState, [e.target. ...

A guide on using Javascript to write information to a JSON file

Let's consider an example where we have a .JSON file with the following content: [{"honda": "accord", "color": "red"},{"ford": "focus", "color": "black"}] We are looking to add another object {"nissan": "sentra", "color": "green"} into this existing ...

Tips for retrieving the 'Created' value in vue.js

I am currently trying to fetch API JSON data for a weather widget, but unfortunately it is returning null. While I am able to retrieve the JSON data successfully, I am struggling to handle this value. Below is my HTML code snippet: <html> <head& ...

Looking to refresh a specific block based on the selection made in another select box?

In the given scenario, my goal is to dynamically update one select box based on the value selected in another select box. For instance: <select id="article" size="4" name="formArticle" style="height:7em;width:16em;border:0px;outline:0px;font-size:16px ...

Adding Node Modules during the setup of an ElectronJS application

Hey there! I'm currently working on an ElectronJS application designed for developers. One of the key features is checking for the presence of NodeJS on the user's computer. If it's not detected, the app will automatically download and insta ...

Displaying content on a webpage using PHP, AJAX, and HTML

Looking to update my current form setup. I have a basic Form below: <form action="" method="POST"> <input type="button" value="Generate Numbers" onclick="on_callPhp1()"/> </form> Accompanied by this javascript code: <script type="te ...

What is the best way to extract value from subscribing?

I attempted to accomplish this task, however, I am encountering issues. Any assistance you can provide would be greatly appreciated! Thank you! export class OuterClass { let isUrlValid = (url:string) => { let validity:boolean ...

Multiple instances of Ajax requests being submitted

I am currently working on updating the validation for my forms. The validation itself is functioning properly, but I have encountered an issue where if no validation errors occur, the form submits multiple times based on the number of submission attempts b ...

A guide to tracing a button click with a personalized <img> tag in Google Tag Manager

Recently, a marketing firm provided me with a custom tag to implement on a Wordpress site for tracking clicks on specific buttons. I am utilizing the Elementor page builder and have assigned unique IDs to each button. Although I am new to Google Tag Manage ...

Discovering Node JS: Pinging UDP between Server and Client

I am new to developing in node.js and I am looking to create a simple script for pinging. My goal is to have the client send a ping to the server, have the server acknowledge it by logging the message in the console, and then send the same packet back to t ...

The event emitted doesn't appear to be caught by EventBus.$on in Vue.js

Currently trying to trigger an event from router.beforeEach and listening for it in another component. Although the vue devtool confirms that the event is being triggered, my component seems unable to capture it. Thank you for your help. This is how I dec ...

When using angular $resource.save for savings, the view is forced to redraw and reflow because of the collection watcher

One of the challenges I'm facing involves loading and storing a model using $resource in AngularJS. This particular model is an aggregate with nested collections, which are displayed in an HTML view using ng-repeat. The structure of the model looks l ...

What is the best way to change an int32 to a float32 in Deeplearn.js?

In December 2017, this code did the job perfectly. However, after updating Deeplearn.js to the latest version, it no longer functions as expected: math.scope(function(keep, track) { var i = track(dl.Array3D.fromPixels(rawImageData, 4)); i = math.multi ...

Include a Vue component within another Vue component in a Laravel application using VueJs

I've recently integrated Vue.js into my Laravel project and encountered an issue when trying to call a component within another component. After running the command npm run dev, I received a webpack error. Here is the code snippet from my parent comp ...