Loop through the XML string inside a for loop using Javascript

Hey everyone, I'm having some trouble with looping through strings for XML inside a for loop. I've attempted the following code but the loop doesn't seem to be working:

var data = [{"name": "Tom", age: "20"}, {"name": "Jerry", age: "20"}]

for (i = 0; i < data.length; i++) {
   var xmltext = '<Placemark>\n' + 
        '\t<name>' + data[i].name + '</name>\n' +
        '\t<age>' + data[i].age + '</age>\n' +
        '</Placemark>';
}

var filename = "file.xml";
var bb = new Blob([xmltext], {type: 'text/xml'});

document.getElementById('download').setAttribute('href', window.URL.createObjectURL(bb));
document.getElementById('download').setAttribute('download', filename);

I'm looking for the following XML result:

<Placemark>
  <name>Tom</name>
  <Age>20</Age>
</Placemark>
<Placemark>
  <name>Jerry</name>
  <Age>20</Age>
</Placemark>

Am I missing something or doing something wrong? Any help would be greatly appreciated.

Answer №1

When iterating through the data array, make sure to only declare the xmltext variable once and then append the strings to it. This will optimize your code and prevent unnecessary variable re-creation.

var data = [{"name": "Alice", age: "25"}, {"name": "Bob", age: "30"}]
var xmltext = "";
for (i = 0; i < data.length; i++) {
xmltext = xmltext + '<Placemark>\n' + 
    '\t<name>' + data[i].name + '</name>\n' +
    '\t<age>' + data[i].age + '</age>\n' +
    '</Placemark>';
}

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

Guide on successfully importing a pretrained model in Angular using TensorFlow.js

I need help with uploading a pretrained Keras model to my existing tensorflow.js model and then making simple predictions by passing tensors in the correct format. The model is stored locally within the project, in the assets folder. export class MotionAn ...

How come Vue.js is not showing the image I uploaded?

Even though I can successfully print the image URL, I'm facing an issue where the img tag is not displaying it, despite my belief that I've bound it correctly. <html> <head> <title>VueJS Split Demo</title> <script t ...

The Art of Repeating: Navigating through a Multi-Layered Array

My PHP Array looks like this: $fruits = array( array("Apple", 1.25), array("Banana", 0.86), ); Desired HTML Output: I want the HTML output to be formatted as follows: Fruit: Apple Price: 1.25 Fruit: Banana Price: 0.86 Attempts Made: I tried ...

Responses were buried beneath the inquiries on the frequently asked questions page

My FAQs page is in pure HTML format. The questions are styled with the css class .pageSubtitle, and the answers have two classes: .p1 and .p2. Here's an example: <p class="pageSubtitle">Which Award should I apply for?</p> <p class="p1" ...

Tips for resolving import errors encountered after running npm start

I recently started using React and I am currently following a tutorial. Even though I have the exact same code as the tutorial, I'm encountering the following error. ./src/index.js Attempted import error: './components/App' does not have a ...

Steps for configuring type definitions for an Apollo error response

Apollo's documentation explains that an error response can take the following form: { "data": { "getInt": 12, "getString": null }, "errors": [ { "message": "Failed to get s ...

Ensuring the presence of an attribute within an AngularJS Directive

Is it possible to determine if a specific attribute exists in a directive, ideally using isolate scope or the attributes object as a last resort? If we have a directive like this <project status></project>, I would like to display a status ico ...

Encountering a node globby error when implementing multiple patterns

Currently, I am successfully using node glob for folder1 as shown below: glob('folder1/*.js'), function(err, files){ if (err) { console.log('Not able to get files from folder: ', err); } else { files.forEach(function (file) ...

Retrieving AJAX data in a Node.js environment

In my HTML application, I am utilizing AJAX to showcase the output on the same page after the submit button is clicked. Before submitting, I am able to retrieve the values passed in the HTML form using: app.use(express.bodyParser()); var reqBody = r ...

Discovering intersection points along a line between the previous and current positions of the mouse in Three.js

I am working on a project in Three.js where I have a scene filled with lines. Everything is working smoothly when the mouse moves slowly, as I am using the raycaster method to check for intersections with the lines. However, the issue arises when the mouse ...

Combining Files in Angular 2 for Optimal Production Deployment

What is the best method for packaging and combining an Angular 2 application for production? My goal is to have an index.html file and a single app.min.js file. Although the Angular 2 documentation mentions using webpack, I found it to be overly complex f ...

What is the ideal approach for setting up the react-native CLI - local module or global installation

I've been following the initial steps to start with React Native from FB's git page at https://facebook.github.io/react-native/docs/getting-started While using nxp or npm installed CLI during the process, I encountered the following error. [!] ...

The use of JQuery repeating fields can cause disruptions to the Bootstrap layout when removing rows

I have been struggling with a form that contains multiple fields that need to be repetitive. My current code is functional, but I'm encountering an issue where clicking on any remove button other than the first one causes the fields in the row to rear ...

Retrieve various key-value pairs from the JSON data in the global market API using AJAX

I have recently developed a real-time API specifically designed for monitoring World Stock Markets. This API covers popular indices such as Nifty, Dow Jones, Nasdaq, and SGX Nifty. If you are interested in accessing this Real Time API, you can do so by vi ...

Tips for updating and using a map value array as state in React

One React state I am working with is as follows: const [tasksMap, setTasksMap] = useState(new Map()); This map is created using the following code: tasks.forEach((task) => { const key = `${week.year}-${week.weekNo}`; if (!tasksMap.has(key)) { ...

Angular Controller encounters issue with event handler functionality ceasing

One of my Angular controllers has the following line. The event handler works when the initial page loads, but it stops working when navigating to a different item with the same controller and template. document.getElementById('item-details-v ...

Access external variables in next.js outside of its environment configuration

Currently, I am developing my application using next js as the framework. While my environment variables work smoothly within the context of next js, I am facing a challenge when it comes to utilizing them outside of this scope. An option is to use dotenv ...

Unlocking the power of module augmentation in Typescript: Enhancing library models within your app domain

I currently work with two applications that share the same code base for their models. I am interested in developing and sharing a library model using inheritance in TypeScript. For instance, Pet extends Author. In my current Angular application, I need ...

Find the positions of elements in a numpy 1D array that are larger than the element that precedes them

Imagine I have created a 1-dimensional numpy array like so: r=np.random.randint(0,10,(10,)) For instance, it might look like this: array([1, 5, 6, 7, 7, 8, 8, 0, 2, 7]) To find the indices where each element is greater than the one before (to the left) ...

Error message: JSON.parse encountered an unexpected "<" token at the start of the JSON input

Currently, I am looping through an object and sending multiple requests to an API using the items in that object. These requests fetch data which is then stored in a database after parsing it with JSON.parse(). The parsed data is sent to a callback functio ...