使用 lib xml2js 为 XML 添加前缀

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}:":`))
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>