如何在angular 4中将xml转换为json? [英] How to convert xml to json in angular 4?
本文介绍了如何在angular 4中将xml转换为json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是angular 4的初学者,我没有足够的知识如何处理XML到JSON以及如何在angular 4中调用Service,请提出
Am a beginner in angular 4, I don't have enough knowledge how to handle XML to JSON and how to call Service in angular 4, please suggest
推荐答案
基于库 http://goessner.net/download/prj/jsonxml/,我实现了一个示例来接收XML数据并将其解析为Angular4应用程序:
Based on the library http://goessner.net/download/prj/jsonxml/, I implemented a sample to receive XML data and parse them into an Angular4 application:
var headers = new Headers();
(...)
headers.append('Accept', 'application/xml');
return this.http.get('https://angular2.apispark.net/v1/companies/', {
headers: headers
}).map(res => JSON.parse(xml2json(res.text(),' ')));
要使用该库,您需要首先解析XML字符串:
To be able to use the library, you need to parse first the XML string:
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
请参阅以下代码: https://plnkr.co/edit/dj63ASQAgrNcLLlwyAum?p=preview.
这篇关于如何在angular 4中将xml转换为json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文