NaturalIntelligence / fast-xml-parser

Validate XML, Parse XML and Build XML rapidly without C/C++ based libraries and no callback.
https://naturalintelligence.github.io/fast-xml-parser/
MIT License
2.45k stars 296 forks source link

Only set textNodeName, build xml is error #589

Closed joneqian closed 1 year ago

joneqian commented 1 year ago

Purpose / Goal

Only set textNodeName, and attributeNamePrefix is empty string, build result is error.

Example:

const schema_obj = {
      field: {
        values: {
          value: {
            '#text': 10061001,
            size: '5',
          },
        },
        id: 'skuCombineContent',
        type: 'multiInput',
      },
    };

    const parse_options = {
      ignoreAttributes: false,
      attributeNamePrefix: '',
      textNodeName: '#text',
    };
    const builder = new XMLBuilder(parse_options);
    const schema_xml = builder.build(schema_obj);

Type

Please mention the type of PR

Test code:

it('xml build test', async () => {
    const schema_obj = {
      field: {
        values: {
          value: {
            '#text': 10061001,
            size: '5',
          },
        },
        id: 'skuCombineContent',
        name: 'skuProduct',
        type: 'multiInput',
      },
    };

    const parse_options = {
      ignoreAttributes: false,
      attributeNamePrefix: '',
      textNodeName: '#text',
    };
    const builder = new XMLBuilder(parse_options);
    const schema_xml = builder.build(schema_obj);
    console.log(schema_xml);
  });

The current code execution results:

<field id="skuCombineContent" name="skuProduct" type="multiInput"><values><value #text="10061001" size="5"></value></values></field>

Modify isAttribute in json2xml.js

function isAttribute(name /*, options*/) {
  if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {
    return name.substr(this.attrPrefixLen);
  } else {
    return false;
  }
}

Get the accurate results:

 <field id="skuCombineContent" name="skuProduct" type="multiInput"><values><value size="5">10061001</value></values></field>