当前位置: 首页 > 工具软件 > go-parse > 使用案例 >

使用fast-xml-parse转object为xml,添加属性标签

孔扬
2023-12-01

准备

安装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 false
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>

参考

GitHub - NaturalIntelligence/fast-xml-parser: Validate XML, Parse XML to JS/JSON and vise versa, or parse XML to Nimn rapidly without C/C++ based libraries and no callback

 类似资料: