情景描述
前端用的是Vue框架,外部提供了一个WebService接口,返回的是XML格式的Array数列。
接口请求
在config下index.js中添加代理表解决跨域问题
proxyTable: {'/api': {target: 'http://xx.xx.xx.xx:xx/DBCenterService/WebService.asmx/GetWaterStr', // 你请求的第三方接口changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题pathRewrite:{ // 路径重写,'^/api': '' // 替换target中的请求地址,也就是说以后你在请求http://xx.xx.xx.xx:xx/DBCenterService/WebService.asmx/GetWaterStr这个地址的时候直接写成/api即可。}}
在相关组件中使用axios请求接口
mounted() {let url = 'api';axios.get(url).then((res) => {let xml_data = res.data;console.log(xml_data);}).catch((err) => {console.log(err)});},
配置改动后需要重启生效(运行npm run dev,即可在控制台看到XML文件内容。
XML解析为JSON
x2js是一个在XML和JavaScript对象之间进行转换的库。转换不一定是无损的,但非常方便。
npm安装
npm i x2js
使用
x2js.xml2js(xml) //xml2js方法,传入xml格式的数据,返回json对象
直接在组件中require()
const x2js = require('x2js')
在执行的方法中使用
var x2jsone = new x2js()var jsonObj = x2jsone.xml2js('<soap:Envelope xmlns:soap="/soap/envelope/" xmlns:xsd="/2001/XMLSchema" xmlns:xsi="/2001/XMLSchema-instance"><soap:Body><ns1:getSDLengthByJMLXResponse xmlns:ns1="http://server.Gw"><ns1:out><?xml version="1.0" encoding="UTF-8"?><NODES><NODE><NAME>方沟</NAME><VALUE>337.9432807</VALUE></NODE><NODE><NAME>砖混</NAME><VALUE>66.8424335</VALUE></NODE><NODE><NAME>盾构</NAME><VALUE>14.8955979</VALUE></NODE><NODE><NAME>暗挖</NAME><VALUE>48.1186321</VALUE></NODE><NODE><NAME>顶管</NAME><VALUE>2.9357091</VALUE></NODE><NODE><NAME>总长度</NAME><VALUE>1272.8081174</VALUE></NODE><NODE><NAME>检查井总数</NAME><VALUE>94885</VALUE></NODE></NODES></ns1:out></ns1:getSDLengthByJMLXResponse></soap:Body></soap:Envelope>')var newjsonObj = x2jsone.xml2js(jsonObj.Envelope.Body.getSDLengthByJMLXResponse.out.__text)for(var i = 0;i<newjsonObj.NODES.NODE.length;i++){console.log(newjsonObj.NODES.NODE[i].NAME)console.log(newjsonObj.NODES.NODE[i].VALUE)}