arturfil
arturfil

Reputation: 450

Converting JSON into XML Angular 7

EDIT: This doesn't work with the xml2js npm package since I want to do the opposite, convert json to xml, not the other way around.

I have my API using JSON data format but I also have to save the object that I updated in a text file in an XML format, since this other application that we communicate with only accepts XML format.

I have my service

shipment.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as x2js from 'xml2js';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ShipmentService {
  baseUrl = "http://localhost:5000/api/shipments/"

  constructor(
    private http: HttpClient
  ) {}


  getShipments() {
    return this.http.get(this.baseUrl);
  }

  getShipment(id) {
    return this.http.get(this.baseUrl + id);
  }

  updateShipment(id: number, shipment) {
    return this.http.put(this.baseUrl + id, shipment);
  }

}

And tracker.component.ts

import { Component, OnInit } from '@angular/core';
import { ShipmentService } from 'src/app/services/shipment.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ShipmentModalComponent } from '../shipment-modal/shipment-modal.component';
import { Router } from '@angular/router';
import { NgxSpinnerService} from 'ngx-spinner';

var convert = require('xml-js');

@Component({
  selector: 'app-tracker',
  templateUrl: './tracker.component.html',
  styleUrls: ['./tracker.component.css']
})
export class TrackerComponent implements OnInit {
  shipments:any = [];
  shipment:any = {};
  modal_on:boolean = false;
  modalcontent:any;
  closeResult = '';
  reference: string;

  constructor(
    private shipmentService: ShipmentService,
    private modalService: NgbModal,
    private spinner: NgxSpinnerService,
    private router: Router
  ) {}

  ngOnInit() {
    this.getShipments();
  }

  convertToXML(json) {
    var options = {compact: true};
    var result = convert.json2xml(json, options);
    console.log(result);
  }

  getShipments() {
    this.spinner.show(undefined,{
      type: "square-spin",
      size: "medium",
      bdColor: 'rgba(0,0,0,.5)',
      color: "rgb(5, 5, 80)",
      fullScreen: false

    });
    this.shipmentService.getShipments().subscribe(response => {

      this.shipments = response;
      this.spinner.hide();

      this.convertToXML(response);

      console.log(response);
    }, error => {  
      console.log(error);
    });

  }

}

So I tried to use x2js and other xml2json libraries but I had no success converting the JSON object into an XML object or string for that matter.

Upvotes: 0

Views: 8909

Answers (2)

arturfil
arturfil

Reputation: 450

So I used js2xmlparser npm package and I wrote the following method on my service.ts file and component.ts file as follows:

service.ts

import * as JsonToXML from 'js2xmlparser';

convertXML(obj) {
    let options = {
      format: {
        doubleQuotes: true
      }, 
      declaration: {
        include: false
      }
    }

    return JsonToXML.parse("UniversalEvent", obj, options);
  }

and in my component.ts file i wrote the following method:

 openModal(content, shipment) {
    // this.modal_on = true;
    let new_obj = {};

    this.modalcontent = shipment;
    this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'});
    new_obj = this.addXmlAttr(new_obj);
    this.xmlShipment = this.shipmentService.convertXML(new_obj);


    console.log(this.xmlShipment)
    console.log(this.modalcontent);
  }

  addXmlAttr(obj) {
    obj = {
      "@": {
        xmlns: "http://www.cargowise.com/Schema/Universal/2011/11",
        version:"1.0"
      },
      Event: {
        DataContext: {
          DataTargetCollection: {
            DataTarget: {
              Type: "ForwardingShipment",
              Key: this.modalcontent.vortex_Reference
            }
          }
        },
        EventTime: this.modalcontent.actual_Pickup,
        EventType: "PCF",
        AdditionalFieldsToUpdateCollection: {
          AdditionalFieldsToUpdate: {
            Type: "ForwardingShipment.DocsAndCartage.JP_PickupCartageCompleted",
            Value: this.modalcontent.actual_Pickup
          }
        }
      }
    }

    return obj;
  }

As somebody suggested, I edited the json object to my specifications and then parsed it to XML and the converted object looks like so:

<UniversalEvent xmlns="http://exampleurl.com/Schema/Example/2011/11" version="1.0">
    <Event>
        <DataContext>
            <DataTargetCollection>
                <DataTarget>
                    <Type>ForwardingShipment</Type>
                    <Key>123456</Key>
                </DataTarget>
            </DataTargetCollection>
        </DataContext>
        <EventTime>2019-05-22T00:00:00</EventTime>
        <EventType>PCF</EventType>
        <AdditionalFieldsToUpdateCollection>
            <AdditionalFieldsToUpdate>
                <Type>ForwardingShipment.DocsAndCartage.JP_PickupCartageCompleted</Type>
                <Value>2019-05-22T00:00:00</Value>
            </AdditionalFieldsToUpdate>
        </AdditionalFieldsToUpdateCollection>
    </Event>
</UniversalEvent>

Upvotes: 1

dasunse
dasunse

Reputation: 3089

install npm i js2xmlparser

import * as JsonToXML from "js2xmlparser";
console.log(JsonToXML.parse("person", this.obj));

Here this.obj is your JSON object

Stackblitz Example

Upvotes: 0

Related Questions