How to convert xml to json in angular

How to convert xml to json in angular




There are many times you required to convert  json from xml and dowloard in json file . there is custom code for generate json from xml 

import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
@Injectable({
  providedIn: 'root'
})
export class XmlToJsonService {

  constructor() { }
  xmlToJson(xml) {

    // Create the return object
    var obj = {};

    if (xml.nodeType == 1) { // element
      if (xml.attributes.length > 0) {
        obj = {};
        for (var j = 0j < xml.attributes.lengthj++) {
          var attribute = xml.attributes.item(j);
          obj[attribute.nodeName] = attribute.nodeValue;
        }
      }
    } else if (xml.nodeType == 3) { // text
      obj = xml.nodeValue;
    }

    // do children
    if (xml.hasChildNodes()) {
      for (var i = 0i < xml.childNodes.lengthi++) {
        var item = xml.childNodes.item(i);
        var nodeName = item.nodeName;
        if (typeof (obj[nodeName]) == "undefined") {
          if (nodeName == '#text') {
            obj = this.xmlToJson(item);
          } else {
            obj[nodeName] = this.xmlToJson(item);
          }
        } else {
          if (typeof (obj[nodeName].push) == "undefined") {
            var old = obj[nodeName];
            obj[nodeName] = [];
            obj[nodeName].push(old);
          }
          obj[nodeName].push(this.xmlToJson(item));
        }
      }
    }
    return obj;
  };

  downloadFile(jsonObject, tradeID) {
    const blob = new Blob([JSON.stringify(jsonObject)], { type: 'application/json' });
    FileSaver(blob, tradeID + '.json');
  }
}


and there is way to call this method

getJson(itemany) {
    console.log(item);
    this.contractService.GetTradeDetail(item.TradeIDitem.IDthis.userId'WithPrevious').then((resany=> {
      if (res['status'] === 200) {
        this.EditForm(res).then((xdata=> {
          const parser = new DOMParser();
          const isDownload = true;
          const xml = '<root><my>hello</my></root>';
          const XMLString = parser.parseFromString(xml"text/xml");
          const JSONString = this.xmlToJsonService.xmlToJson(XMLString);
          if (isDownload) {
            this.dealFastXMLService.generateXml(this.trademodeltrueisDownload);
            this.xmlToJsonService.downloadFile(JSONStringthis.trademodel.ReferenceNo);
          }
          
        });
      }
    });
  }

No comments:

Post a Comment

Thank You For Your Great Contribution

Featured Post

how to find n number of nodes have child or cildren

 how to find n number of nodes have child or cildren for that we use recursive function  const   data = {     'id' : '0' ,...

Popular Posts