简体   繁体   English

使用 lib xml2js 为 XML 添加前缀

[英]Add prefix to XML with lib xml2js

When going from XML to JS, the "processors.stripPrefix" allows you to remove the prefix.从 XML 到 JS 时,“processors.stripPrefix”允许您删除前缀。 Is there any option to add prefix?有没有添加前缀的选项?

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>

Any solution please??请问有什么解决办法吗??

Based on the official documentation it does not have a feature to add prefixed keys.根据官方文档,它没有添加前缀键的功能。

You'd have to add them yourself.您必须自己添加它们。 So this is a workaround that would work for simple objects所以这是一种适用于简单对象的解决方法

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)

This will produce这将产生

<?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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM