Skip to main content

How to Read XML File data in Angular 8

Introduction

In this post, we'll learn about reading XML file in Angular 8. Reading XML files is very important in certain circumstances, especially when the server returns the data in XML format.

We will use a static XML file stored in the local system in the assets folder of our project.

Prerequisites

  • Basic knowledge of Angular 7
  • Visual Studio Code installed on the system
  • Angular CLI installed on the system
  • NodeJS must be installed

XML File

<?xml version="1.0" encoding="UTF-8"?>    
<Employee>    
   <emp>    
      <id>1</id>    
      <name>Faisal</name>    
      <gender>Male</gender>    
      <mobile>514545</mobile>    
   </emp>    
   <emp>    
      <id>2</id>    
      <name>Bhavdip</name>    
      <gender>Male</gender>    
      <mobile>5431643</mobile>    
   </emp>    
   <emp>    
      <id>3</id>    
      <name>Irshad</name>    
      <gender>Male</gender>    
      <mobile>43265436</mobile>    
   </emp>    
   <emp>    
      <id>4</id>    
      <name>Keyur</name>    
      <gender>Male</gender>    
      <mobile>5435431</mobile>    
   </emp>    
   <emp>    
      <id>5</id>    
      <name>Tabish</name>    
      <gender>Male</gender>    
      <mobile>432656</mobile>    
   </emp>    
</Employee>    

Create a new project in Angular 8 by typing the following command.

ng new read-xml-angular8 --routing 

After creating the project, open the project in your favorite editor and install the "timers" npm package. 

npm install timers 

This package is necessary for reading an XML file with xml2js package.

Open the index.html present at root folder and add a reference for Bootstrap and jQuery.

<!doctype html>   
<html lang="en">  
   <head>  
      <meta charset="utf-8">  
      <title>ReadXmlAngular8</title>  
      <base href="/">  
      <meta name="viewport" content="width=device-width, initial-scale=1">  
      <link rel="icon" type="image/x-icon" href="favicon.ico">  
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>   
   </head>  
   <body>  
      <app-root></app-root>  
   </body>  
</html> 

Open the app.component.ts file and add the following code in it. 

import { Component } from '@angular/core';  
import xml2js from 'xml2js';  
import { HttpClient, HttpHeaders } from '@angular/common/http';  
@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
  title = 'read-xml-angular8';  
  public xmlItems: any;  
  constructor(private _http: HttpClient) { this.loadXML(); }  
  loadXML() {  
    this._http.get('/assets/users.xml',  
      {  
        headers: new HttpHeaders()  
          .set('Content-Type', 'text/xml')  
          .append('Access-Control-Allow-Methods', 'GET')  
          .append('Access-Control-Allow-Origin', '*')  
          .append('Access-Control-Allow-Headers', "Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Request-Method"),  
        responseType: 'text'  
      })  
      .subscribe((data) => {  
        this.parseXML(data)  
          .then((data) => {  
            this.xmlItems = data;  
          });  
      });  
  }  
  parseXML(data) {  
    return new Promise(resolve => {  
      var k: string | number,  
        arr = [],  
        parser = new xml2js.Parser(  
          {  
            trim: true,  
            explicitArray: true  
          });  
      parser.parseString(data, function (err, result) {  
        var obj = result.Employee;  
        for (k in obj.emp) {  
          var item = obj.emp[k];  
          arr.push({  
            id: item.id[0],  
            name: item.name[0],  
            gender: item.gender[0],  
            mobile: item.mobile[0]  
          });  
        }  
        resolve(arr);  
      });  
    });  
  }  
} 

Here is the code for app.component.html file.

<div class="container">    
  <table class="table table-bordered table-hover">    
    <tr>    
      <th>Id</th>    
      <th>Name</th>    
      <th>Gender</th>    
      <th>Mobile</th>    
    </tr>    
    <tr *ngFor="let item of xmlItems">    
      <td>{{item.id}}</td>    
      <td>{{item.name}}</td>    
      <td>{{item.gender}}</td>    
      <td>{{item.mobile}}</td>    
    </tr>    
  </table>    
</div>    

Finally, add the HttpClientModule reference in the app.module.ts file and that’s it.

import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';  
import { AppRoutingModule } from './app-routing.module';  
import { AppComponent } from './app.component';  
import { HttpClientModule } from '@angular/common/http';  
@NgModule({  
  declarations: [  
    AppComponent  
  ],  
  imports: [  
    BrowserModule,  
    AppRoutingModule,  
    HttpClientModule  
  ],  
  providers: [],  
  bootstrap: [AppComponent]  
})  
export class AppModule { }  

Output

This is image title

Please give your valuable feedback/comments/questions about this article. Please let me know if you liked and understood this article and how I could improve it.

Thank for reading!

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...