vue中使用x2js实现xml和json互转

下载x2js

cnpm i -S x2js

全局引入

import x2js from 'x2js'
Vue.prototype.$x2js = new x2js()

使用

  mounted() {
    console.log("this.$x2js:", this.$x2js);

    let xmlstr = `<?xml version="1.0" encoding="UTF-8"?>
          <note>
          <to>Tove</to>
          <from>Jani</from> 
          <heading>Reminder</heading>
          <body>Don't forget me this weekend!</body>
          </note>`;

    console.log("xmlstr:", xmlstr);

    console.log("xml转json:", this.$x2js.xml2js(xmlstr));

    console.log("json转xml:", this.$x2js.js2xml(this.$x2js.xml2js(xmlstr)));
  },

下载xml文件到本地

  mounted() {
    let xmlstr = `<?xml version="1.0" encoding="UTF-8"?>
          <note>
          <to>Tove</to>
          <from>Jani</from> 
          <heading>Reminder</heading>
          <body>Don't forget me this weekend!</body>
          </note>`;
    let url = window.URL.createObjectURL(
      new Blob([xmlstr], { type: "text/xml" })
    );
    // 然后就可以创建a标签 最后下载下来了
    let link = document.createElement("a");
    // 不显示链接
    link.style.display = "none";
    link.href = url;
    // 设置链接属性
    link.setAttribute("download", "xmlstr");
    //点击链接
    document.body.appendChild(link);
    link.click();
  },

生成的xml字符串格式化

参考:https://blog.csdn.net/qq_40323256/article/details/127036957icon-default.png?t=M85Bhttps://blog.csdn.net/qq_40323256/article/details/127036957

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值