使⽤fast-xml-parse转object为xml,添加属性标签
准备
安装fast-xml-parser@3.3.4
npm install fast-xml-parser@3.3.4
重点属性
attributeNamePrefix : prepend given string to attribute name for identification
attrNodeName: (Valid name) Group all the attributes as properties of given name.
ignoreAttributes : Ignore attributes to be parsed.
tagValueProcessor : Process tag value during transformation. Like HTML decoding, word capitalization, etc. Applicable in case of string only.
attrValueProcessor : Process attribute value during transformation. Like HTML decoding, word capitalization, etc.
Applicable in case of string only.
attributeNamePrefix:'@_',
attrNodeName:'@',//default is falseposition标签属性
ignoreAttributes:false,
attrValueProcessor:(val, attrName)=>
he.decode(val,{ isAttributeValue:true}),//default is a=>a
tagValueProcessor:(val, tagName)=> he.decode(val),//default is a=>a
⽰例
对象
export const mbbalqry ={
stream:[
{
action:'MBBALQRY',
userName:'citic',
list:[
{
row:[
{
accountNo:'8110801013201236512',
},
],
'@_name':'userDataList',
},
],
bankType:'CITIC',
startRecord:'1',
pageNumber:'20',
},
],
};
代码
import*as fxp from'fast-xml-parser';
import*as he from'he';
export const objToXml=(obj: Object)=>{
var Parser = fxp.j2xParser;
//default options need not to set
var defaultOptions ={
attributeNamePrefix:'@_',
attrNodeName:'@',//default is false
textNodeName:'#text',
ignoreAttributes:false,
ignoreNameSpace:false,
cdataTagName:false,//default is false
cdataPositionChar:'\\c',
format:true,
indentBy:'    ',
supressEmptyNode:false,
attrValueProcessor:(val, attrName)=>
he.decode(val,{ isAttributeValue:true}),//default is a=>a
tagValueProcessor:(val, tagName)=> he.decode(val),//default is a=>a };
const parser =new Parser(defaultOptions);
let xmlstr = parser.parse(obj);
xmlstr ='<?xml version="1.0" encoding="GBK"?>'+ xmlstr;
return xmlstr;
};
结果
<?xml version="1.0" encoding="GBK"?><stream>
<action>MBBALQRY</action>
<userName>citic</userName>
<list name="userDataList">
<row>
<accountNo>8110801013201236512</accountNo>
</row>
</list>
<bankType>CITIC</bankType>
<startRecord>1</startRecord>
<pageNumber>20</pageNumber>
</stream>
参考

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。