typescript 在angular2中读取xml文件数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42577492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read xml file data in angular2
提问by Basil Joy
In the Angular2 project, I have one xml file that contains all information about an employee. i need to read employee data from that xml
file and display in my component template.
在 Angular2 项目中,我有一个 xml 文件,其中包含有关员工的所有信息。我需要从该xml
文件中读取员工数据并显示在我的组件模板中。
How to read xml data using http service?
如何使用http服务读取xml数据?
回答by dpetrini
For parsing you can try with xml2js: https://github.com/Leonidas-from-XIV/node-xml2js.
对于解析,您可以尝试使用 xml2js:https: //github.com/Leonidas-from-XIV/node-xml2js。
Check this other answer: XML data parsing in angular 2
检查另一个答案: XML data parsing in angular 2
In a short:
简而言之:
import { parseString } from 'xml2js';
/* ... */
let xml = "<root>Hello xml2js!</root>"
parseString(xml, function (err, result) {
console.dir(result);
});
回答by wkrueger
The browser API already comes with an XML parser. Have a look at.
浏览器 API 已经带有一个 XML 解析器。看一下。
https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML
https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML
After you succeed parsing the document, you will navigate it with an API similar to the DOM navigation.
成功解析文档后,您将使用类似于 DOM 导航的 API 对其进行导航。
Some HTTP client libs may come with an option to parse XML (dont install a new one just to do that, check the one you are using!). I also had a quick look at angular's HttpClient and didnt find any XML parsing option on it at first.
某些 HTTP 客户端库可能带有解析 XML 的选项(不要为此安装新库,请检查您正在使用的库!)。我还快速浏览了 angular 的 HttpClient,但一开始并没有找到任何 XML 解析选项。
The old XMLHttpRequest APIalso comes with an option to directly parse the response as XML (.responseXML
), but you probably wont use it since you may be already using another thing for your HTTP client.
旧的XMLHttpRequest API还带有一个选项,可以将响应直接解析为 XML ( .responseXML
),但您可能不会使用它,因为您可能已经在为您的 HTTP 客户端使用其他东西。
回答by Roman C
You can do it with jQuery.parseXML, but you need to integrate jQuery with Angular.
您可以使用jQuery.parseXML 来完成,但您需要将 jQuery 与 Angular 集成。
jQuery.parseXML
uses the native parsing function of the browser to create a valid XML Document. This document can then be passed to jQuery to create a typical jQuery object that can be traversed and manipulated.
jQuery.parseXML
使用浏览器的本机解析功能来创建有效的 XML 文档。然后可以将此文档传递给 jQuery 以创建一个典型的 jQuery 对象,该对象可以被遍历和操作。
For more details to integrate with jQuery see How to use jQuery with Angular2.
有关与 jQuery 集成的更多详细信息,请参阅如何在 Angular2 中使用 jQuery。
Using http service
使用http服务
let xml = "";
this.http.get(url)
.map((res:Response) => res.text())
.subscribe(data => {
xml = data;
console.log($.parseXML(xml));
});