扫一扫分享
下载方法
npm install xml2js
实例如下
var xml2js = require('xml2js');
//xml->json
//xml2js默认会把子子节点的值变为一个数组, explicitArray设置为false
var xmlParser = new xml2js.Parser({explicitArray : false, ignoreAttrs : true})
//json->xml
var jsonBuilder = new xml2js.Builder();
//测试用例
var xml = "<root>Hello xml2js!</root>";
var obj = {name: "Super", Surname: "Man", age: 23};
console.log('----------');
// xml -> json
xmlParser.parseString(xml, function (err, result) {
//将返回的结果再次格式化
console.log(JSON.stringify(result));
});
console.log('----------');
//json --> xml
var builder = new xml2js.Builder();
var jsonxml = builder.buildObject(obj);
console.log(jsonxml);
console.log('----------');
结果如下
----------
{"root":"Hello xml2js!"}
----------
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<name>Super</name>
<Surname>Man</Surname>
<age>23</age>
</root>
----------
手机预览