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 = 0; j < xml.attributes.length; j++) {
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 = 0; i < xml.childNodes.length; i++) {
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(item: any) {
console.log(item);
this.contractService.GetTradeDetail(item.TradeID, item.ID, this.userId, 'WithPrevious').then((res: any) => {
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.trademodel, true, isDownload);
this.xmlToJsonService.downloadFile(JSONString, this.trademodel.ReferenceNo);
}
});
}
});
}
No comments:
Post a Comment
Thank You For Your Great Contribution