Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将JSON转换为XML 7_Javascript_Json_Angular_Xml_Angular7 - Fatal编程技术网

Javascript 将JSON转换为XML 7

Javascript 将JSON转换为XML 7,javascript,json,angular,xml,angular7,Javascript,Json,Angular,Xml,Angular7,编辑:这不适用于xml2js npm包,因为我想做相反的事情,将json转换为xml,而不是反过来 我的API使用JSON数据格式,但我还必须以XML格式将更新的对象保存在文本文件中,因为我们使用的另一个应用程序只接受XML格式 我有我的服务 装运服务 import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import * as x2js from 'xml2j

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

我的API使用JSON数据格式,但我还必须以XML格式将更新的对象保存在文本文件中,因为我们使用的另一个应用程序只接受XML格式

我有我的服务

装运服务

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

}

import * as JsonToXML from 'js2xmlparser';

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

    return JsonToXML.parse("UniversalEvent", obj, options);
  }
和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对象或字符串

安装
npm i js2xmlparser

import * as JsonToXML from "js2xmlparser";
console.log(JsonToXML.parse("person", this.obj));
这里
this.obj
是您的JSON对象


因此我使用了js2xmlparser npm包,并在service.ts文件和component.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);
  }

}

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>

转运
123456
2019-05-22T00:00:00
PCF
ForwardingShipment.DocsAndCartage.JP\u提货车已完成
2019-05-22T00:00:00

请给出一个答案;“不成功”到底意味着什么?在代码中的什么地方进行转换?我添加了请求对象的依赖项和方法,在那里我需要将json响应转换为xml对象。如果有json对象数组呢?对于每个json对象,其结果xml文件中将包含person标记。如何将其限制为仅一个根标记/节点?