首页 > 解决方案 > 将 JSON 转换为 XML Angular 7

问题描述

编辑:这不适用于 xml2js npm 包,因为我想做相反的事情,将 json 转换为 xml,而不是相反。

我的 API 使用 JSON 数据格式,但我还必须将更新的对象保存在 XML 格式的文本文件中,因为我们与之通信的其他应用程序只接受 XML 格式。

我有我的服务

装运服务.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);
  }

}

和 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);
    });

  }

}

所以我尝试使用 x2js 和其他 xml2json 库,但我没有成功地将 JSON 对象转换为 XML 对象或字符串。

标签: javascriptjsonangularxmlangular7

解决方案


所以我使用了 js2xmlparser npm 包,并在我的 service.ts 文件和 component.ts 文件上编写了以下方法,如下所示:

服务.ts

import * as JsonToXML from 'js2xmlparser';

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

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

在我的 component.ts 文件中,我编写了以下方法:

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

正如有人建议的那样,我将 json 对象编辑为我的规范,然后将其解析为 XML,转换后的对象如下所示:

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

推荐阅读