x2js源码地址
GitHub - abdolence/x2js: x2js - XML to JSON and back for JavaScriptx2js - XML to JSON and back for JavaScript. Contribute to abdolence/x2js development by creating an account on GitHub.https://github.com/abdolence/x2js
import x2js from 'x2js';//npm install x2js
Vue.prototype.$x2js = new x2js();
...
<script>
export default {
created() {
let json = {
MyRoot: {
test1: "测试值1",
test2: {
item: ["测试值2-1", "测试值2-2"],
},
},
};
console.log(`JSON to XML`, this.$x2js.js2xml(json));
let xml =
"<MyRoot><test1>测试值1</test1><test2><item>测试值2-1</item><item>测试值2-2</item></test2></MyRoot>";
console.log(`XML to JSON`, this.$x2js.xml2js(xml));
},
};
</script>
请注意,这个简单的例子不会处理属性或者特殊字符转义等复杂情况。如果你的JSON对象中包含属性或者特殊字符,你可能需要编写更复杂的逻辑来处理这些情况。
输出结果