[英]Add prefix to XML with lib xml2js
从 XML 到 JS 时,“processors.stripPrefix”允许您删除前缀。 有没有添加前缀的选项?
const jsonObj = {
foo: {
bar: {
hello: 'world'
}
}
};
const builder = new xml2js.Builder();
const xml = builder.buildObject(jsonObj);
console.log(xml);
//I need this result
<prefix:foo>
<prefix:bar>
<prefix:hello>world</prefix:hello>
</prefix:bar>
</prefix:foo>
请问有什么解决办法吗??
根据官方文档,它没有添加前缀键的功能。
您必须自己添加它们。 所以这是一种适用于简单对象的解决方法
const xml2js = require('xml2js')
const jsonObj = {
foo: {
bar: {
hello: 'world'
}
}
}
const builder = new xml2js.Builder()
const prefix = 'abc'
const prefixedObj = JSON.parse(
JSON.stringify(jsonObj)
.replace(/"([^"]+)":/g, `"${prefix}:$1":`))
const xml = builder.buildObject(prefixedObj)
console.log(xml)
这将产生
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<abc:foo>
<abc:bar>
<abc:hello>world</abc:hello>
</abc:bar>
</abc:foo>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.