Node.js 使用 xml2js 从结果 XML 中删除根节点 [英] Node.js remove root node from resulting XML using xml2js
本文介绍了Node.js 使用 xml2js 从结果 XML 中删除根节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从 JSON obj 创建一个 XML 并在结果中给我根元素,我尝试设置 explicitRoot var parser = xml2js.Parser({explicitRoot:false});
为 false 但它不会删除默认的根标记,而只是删除我的原始 XML 根标记 (<VSAT></VSAT>)
I'm trying creating a XML from JSON obj and its giving me root element in the result, I tried setting the explicitRoot var parser = xml2js.Parser({explicitRoot:false});
to false but it does not remove the default root tag but just removing my orignal XML root tag (<VSAT></VSAT>)
使用 xml2js
<?xml version="1.0" encoding="utf-8"?>
<VAST version="2.0">
<Ad id="72419"></Ad>
</VAST>
结果 XML:
<?xml version="1.0" encoding="utf-8"?>
<root>
<VAST version="2.0">
<Ad id="72419"></Ad>
</VAST>
</root>
有什么想法吗?
完整代码
/*
NodeJS server
*/
var http = require('http');
var xml2js = require('xml2js');
var fs = require('fs');
var util = require('util');
var json,PORT=2000;
var server = http.createServer(function(request, response){
response.writeHead(200,{'Content-Type':'text/html'});
try{
var filedata = fs.readFileSync('vast_all.xml','ascii');
var parser = xml2js.Parser({explicitRoot:true});
parser.parseString(filedata.substring(0,filedata.length),function(err,result){
result.new = 'test';
json = JSON.stringify(result);
var builder = new xml2js.Builder({
xmldec:{ 'version': '1.0', 'encoding': 'UTF-8' },
cdata:true,
});
var xml = builder.buildObject(json);
response.write(json);
/*console.log(util.inspect(builder, false, null));*/
});
response.end();
}
catch(e){
console.log(e);
}
});
console.log("Server running at port "+PORT);
try{
server.listen(PORT);
}
catch(e){
console.log(e);
}
推荐答案
您不能删除根节点,但可以像这样更改其名称:
you can't remove root node but you can change its name like this:
let builder = new xml2js.Builder({headless: true , explicitRoot : false , rootName :'Search_Query'});
let xml = builder.buildObject(req.param('Search_Query'));
这会将 root
更改为 Search_Query
这篇关于Node.js 使用 xml2js 从结果 XML 中删除根节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文