Read XML File In Angular

Read XML File In Angular

In this article, we will learn how to read XML files in Angular. When the server provides the data in XML format, it is sometimes crucial to read the XML file.

We will make use of the static XML file that is kept on the local system in the project's assets folder.

Sample XML File:

<?xml version="1.0"?>  
<Employee>  
    <emp>  
        <id>1</id>  
        <name>Chirag</name>  
        <gender>Male</gender>  
        <mobile>234324234</mobile> 
    </emp>  
    <emp>  
        <id>2</id>  
        <name>Mehul</name>  
        <gender>Male</gender>  
        <mobile>5245545</mobile>
    </emp>  
    <emp>  
        <id>3</id>  
        <name>Jigar</name>  
        <gender>Male</gender>  
        <mobile>523545443</mobile> 
    </emp>  
    <emp>  
        <id>4</id>  
        <name>Keyur</name>  
        <gender>Male</gender>  
        <mobile>32543543543</mobile>
    </emp>  
    <emp>  
        <id>5</id>  
        <name>Kevin</name>  
        <gender>Male</gender>  
        <mobile>342552543</mobile>  
    </emp>  
</Employee>

So, let's start with the implementation

First, we need to create a new angular application using the following command in the terminal.

ng new read-xml-angular

Now, we need to install timers npm packages using the following command in the terminal.

npm install timers

this package is required to the read an XML file using xml2js package.

Now, add the Bootstrap and jQuery reference in the index.html file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Read Xml Angular</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>

Now, add the HttpClientModule module in the app.module.ts file using the following code.

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 { }

Now, add the following code under the app.component.ts file.

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-angular';
  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);
      });
    });
  }
}

Now, add the following code under the 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>

Now, run the application using the ng serve command into the terminal and see the browser screen, now we are able to read XML file and display into the HTML table format. 

Conclusion

In this article, we learned how to read XML file in angular using the xml2js packages.

I hope this article helps you and you will like it.👍

Please give your valuable feedback and comments or suggestion in the comment section

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post