Using angular2's ngRepeat to iterate over XML data

I have successfully transformed my XML data into JSON format to be utilized in Angular 2 within my view. However, as I attempt to loop through the data using a for(var... loop, I encounter an error message stating that it cannot find name array and that the property lenght does not exist on type Document.

getXml() {
   this.http.get('../../xmlConf/dashboard_journey.xml')
    .map(response => response.text())
    .subscribe(data => {
        if(data) {
            var parser = new DOMParser();
            var xmlData = parser.parseFromString(data, "application/xml");

            for (var index = 0; index < xmlData.length; index++) {
                var element = xmlData[index];

            }
        }
    });
}

The aforementioned line will retrieve the XML data that needs to be iterated through.

var xmlData = parser.parseFromString(data, "application/xml");

My XML Data consists of 5 of these:

<journey>
<title>Click and Collect</title>
<shortDesc>
    <short_desc_1>lorem</short_desc_1>
    <short_desc_2>lorem</short_desc_2>
</shortDesc>
<longDesc>
    lorem
</longDesc>
<imageName>
    <img src="/journey_images/clickandcollect.jpg" alt="Click and Collect"/>
</imageName>

Desired End Result:

In Angular 1, when working with JSON format data received from the server, you can access items like data.obj or use ng-repeat in HTML to display the response data.

<div ng-repeat="item in items">
 <div>{{item.title}}</div>
 <div>{{item.longDesc}}</div>
 <div>{{item.imageName}}</div>
</div>

Answer №1

DOMParser.parseFromString function will give you a Document object.

First step is to determine what you want to iterate through. For instance, if your goal is to loop over all journey tags, you can use the following code:

var journeys = xmlData.getElementsByTagName('journey');

This will provide you with a collection of Element objects that are ready for iteration.

Answer №2

If you want to iterate over nodes in the document received from the DOMParser, you are limited to only looping within that specific document.

By using

var tags = xmlData.getElementsByTagName('journey')
, you can access all nodes and iterate through them as needed.

var node= xmlData.getElementsByTagName('*');
for (var i = 0; i < node.length; i++) {
    alert(node[i].nodeName + ' = ' + node[i].firstChild.nodeValue);
}

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

VueJS does not refresh other components in the application

I am working with two components. Let's start with Component 1: <template> <div> <div class="form-group"> <label for="group">Category</label> <select name="category" v-model="category" @change="setCategory(ca ...

Tips for streamlining the use of hidden and visible div elements with concise code

I have been attempting to use the same code for multiple modules on this page, but none of the methods I've tried seem to be effective. I want to avoid endlessly duplicating existing code. document.addEventListener('DOMContentLoaded', fun ...

Angular is having trouble with binding

What seems to be the issue in this code snippet? JSFiddle. function SecondCtrl($scope, Data) { $scope.data = Data; $scope.reversedMessage = function(message) { return message.split("").reverse().join(""); }; } ...

All Event Monitor

Is it possible to use Event Listeners in jQuery to display information when a specific word is clicked? For example, showing a definition when a word is clicked. Thanks, Adam. I need help with creating a feature where clicking on a person's name in a ...

After closing and reopening the jQuery modal, the name does not appear

I crafted a custom modal window to display images along with comments and the owner's name. The issue arises when I close the current modal and reopen it; the owner's name disappears. Oddly enough, the name is displayed the first time the modal i ...

Ways to forward a parameter to a different web address?

Is there a way to properly redirect a parameter such as http://example.com/?link=https://google.com to its destination at ? ...

When you click on Highcharts, a bigger graph will be displayed

I am working on a feature that allows users to zoom in on small charts on my website. This involves revealing an overlay div and displaying a larger chart with the same data as the clicked chart inside it. function DrawSmallChart() { chart_data = [1, 2, 3 ...

HTML elements generated dynamically do not possess any jQuery properties

I have implemented a draggable list of Div elements using jQuery. Here is the code: <div id="external-events"> <h4>List Of Staffs</h4> <div class="external-event" data-id="1">Name</div> //Draggab ...

What sets Observables (Rx.js) apart from ES2015 generators?

From what I've gathered, there are various techniques used for solving asynchronous programming workflows: Callbacks (CSP) Promises Newer methods include: Rx.js Observables (or mostjs, bacon.js, xstream etc) ES6 generators Async/Await The trend ...

`html2canvas encountered an issue: Unable to locate a logger instance`

When I use html2canvas to render the same content repeatedly, I encounter an error about 5% of the time. It seems to be sporadic and I'm not sure why it occurs. What could be causing this unpredictable behavior? html2canvas.js:2396 Uncaught (in promi ...

Having trouble with boolean in Typescript and Angular 2?

I've encountered an unusual issue while populating a model from an API response. Here's how my model appears: import {Company} from './../api/odata/data/Company'; export class MyModel { ... isEnabled = false; .... constructor(dat ...

Retrieving Information from Ajax Response Following a Successful Insert Query in Codeigniter

I am trying to use ajax method to insert form data into a database and then redirect it to the next page. I have successfully passed the data in ajax and inserted it into the database table. However, I am facing an issue with getting the generated referenc ...

Creating a delay before each new object is added to an array within a loop

I have a code for loop that needs to send an AJAX request with a one second delay between each iteration. It should take the object and add it to the array using .push method. However, my current implementation only adds the first object to the array. Ca ...

Guide to implement editable columns in Angular 4 with a click functionality

I have a table displaying records using ngFor, and I am looking to enable editing of a column upon clicking it. <tr *ngFor="let cd of descriptionCodes; let i = index"> <td><input type="checkbox"></td> <td> {{cd.code}} ...

Tips on generating an HTML element using JavaScript and storing it in a MySQL database

I need help with saving a created element to the database so that it remains on the page even after refreshing. Any assistance would be greatly appreciated. Thank you. document.getElementById("insert").onclick = function(){ if(document.getElementById( ...

Guide on setting and retrieving values with a service using a map function

I have a shared HTML <inventory-products-list *ngIf="toggle" [products]="products" (qrCode)="generateQRCode($event)" (undeleted)="undelete($event)" (deleted)="deleteProduct($event)"></inventory-products-list> this I need to use in different ...

Is it feasible to pre-load external websites using JavaScript?

While searching on various platforms, including Stack Overflow, I couldn't find a solution to this specific query. I'm not necessarily seeking an implementation already in place, but rather ... Imagine having an intranet application that loads q ...

methods for transferring javascript variables to modal

<div> <h5> <a href="<?php echo base_url(); ?>/vendor/home/projects" >Return to Projects</a> </h5> <div> <div class="container"> <div class="row"> ...

Attempting to publish and install a unique angular2 component using NPM and Angular-CLI results in successful compilation only on the initial try

I am facing a peculiar and frustrating issue. The problem revolves around an Ng2 component I have developed called via-date-picker. My goal is to publish it on NPM so that it can be easily utilized in other projects. To achieve this, I converted it into a ...

Using TypeScript to Verify the Existence of Words in a String

Is there a way in typescript to find specific words within a given string? For example: If we have a list: ['Mr', 'Mrs', 'FM.', 'Sir'] and a string named 'Sir FM. Sam Manekshaw'. The words 'Sir' ...