[英]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.