使用fast-xml-parser v4.3.6构建XML时,如何保留属性的true值?
fast-xml-parser 4.3.6 问题解决
需求
需要生成带tokenized="true"属性的XML标签,示例如下:
<custom-tag tokenized="true">test test > 14</custom-tag>
现有代码
配置与测试数据
const defaultXmlOptions = { ignoreAttributes: false, attributeNamePrefix: "@_", indentBy: " ", textNodeName: "#text", format: true, }; const testJson = { component: { "custom-tag": { "#text": "test test > 14", "@_tokenized": true } } };
当前转换逻辑
const parser = new XMLBuilder(defaultXmlOptions); const xml = parser.build(testJson);
当前输出问题
生成的XML中布尔属性省略了="true"部分,不符合需求:
<component> <custom-tag tokenized>test test > 14</custom-tag> </component>
期望输出
<component> <custom-tag tokenized="true">test test > 14</custom-tag> </component>
原可行方案(不适配Vite)
之前用CommonJS的require调用j2xParser可以正常生成带值的布尔属性,但项目从CRA迁移到Vite后无法使用require:
var Parser = require("fast-xml-parser").j2xParser; var parser = new Parser(defaultXmlOptions); var xml = parser.parse(testJson);
适配Vite的解决方案
改用ES模块导入j2xParser,并添加suppressBooleanAttributes: false配置(默认该值为true,会省略布尔属性的属性值):
修改后代码
// ES模块导入方式 import { j2xParser } from 'fast-xml-parser'; const defaultXmlOptions = { ignoreAttributes: false, attributeNamePrefix: "@_", indentBy: " ", textNodeName: "#text", format: true, suppressBooleanAttributes: false // 关键配置:保留布尔属性的="true"值 }; const testJson = { component: { "custom-tag": { "#text": "test test > 14", "@_tokenized": true } } }; // 使用j2xParser生成XML const parser = new j2xParser(defaultXmlOptions); const xml = parser.parse(testJson);
执行上述代码即可生成符合需求的XML,同时适配Vite的ES模块环境。
内容的提问来源于stack exchange,提问作者Howdy
相关产品推荐
相关产品推荐

