我们要导出的xml文件格式是这样的。那要怎么做呢?
首先呢 安装 x2js 插件
npm i x2js
然后在main.js中引入
import x2js from 'x2js' //xml数据处理插件
Vue.prototype.$x2js = new x2js() //全局挂载到vue原型上
下面是导出xml文件的代码
// 导出函数
exportXml() {
// 这里遍历数据,排好我们上面需要的xml格式
let arr = this.tableData.map((item) => {
let json = {};
json._account = item.fund_account;
json.ips = "";
json.macs = {};
json.macs.mac = [];
let ipArr = item.ipmac.split(";");
ipArr.map((val) => {
json.macs.mac.push({
_addr: val,
});
});
return json;
});
console.log(arr) // 1111
let obj = {
bwlist: {
_type: "white",
acc: arr,
},
};
console.log(obj) // 2222
// 调用$x2js 将我们的json数据转换成xml数据格式
let xml = this.$x2js.js2xml(obj);
console.log(xml) // 下面就是我们想要的xml文件的数据格式了
// <bwlist type="white">
// <acc account="0020047843">
// <ips />
// <macs>
// <mac addr="1C872CCC0400" />
// <mac addr="308D99148364" />
// </macs>
// </acc>
// </bwlist>
let url = window.URL.createObjectURL(
new Blob([xml], { type: "text/xml" })
);
console.log(url)
// 这里会生成一个url blob:http://www.ceshi.com:111/5a8d3b47-a3e9-40ba-8341-ebb2016fe5f8
// 然后就可以创建a标签 最后下载下来了
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download","导出的文件名字");
document.body.appendChild(link);
link.click();
1111 这里呢,就是我们console.log(arr)打印的数据了
2222 这里呢,就是我们console.log(obj)打印的数据了