为了账号安全,请及时绑定邮箱和手机立即绑定

使用 lib xml2js 向 XML 添加前缀

使用 lib xml2js 向 XML 添加前缀

慕婉清6462132 2022-08-18 15:43:59
当从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>任何解决方案请??
查看完整描述

1 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

根据官方文档,它没有添加前缀键的功能。


您必须自己添加它们。因此,这是一种适用于简单对象的解决方法。


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>


查看完整回答
反对 回复 2022-08-18
  • 1 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号