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

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...