使用 lib xml2js 向 XML 添加前缀

当从XML到JS时,“processor.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>

任何解决方案请??


慕婉清6462132
浏览 63回答 1
1回答

眼眸繁星

根据官方文档,它没有添加前缀键的功能。您必须自己添加它们。因此,这是一种适用于简单对象的解决方法。const xml2js = require('xml2js')const jsonObj = {&nbsp; foo: {&nbsp; &nbsp; bar: {&nbsp; &nbsp; &nbsp; hello: 'world'&nbsp; &nbsp; }&nbsp; }}const builder = new xml2js.Builder()const prefix = 'abc'const prefixedObj = JSON.parse(&nbsp; JSON.stringify(jsonObj)&nbsp; &nbsp; .replace(/"([^"]+)":/g, `"${prefix}:$1":`))const xml = builder.buildObject(prefixedObj)console.log(xml)这将产生<?xml version="1.0" encoding="UTF-8" standalone="yes"?><abc:foo>&nbsp; <abc:bar>&nbsp; &nbsp; <abc:hello>world</abc:hello>&nbsp; </abc:bar></abc:foo>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript