fast-xml-parser version 4.3.6
Description
I need to include xml attribute (tokenized="true"), like this : <custom-tag tokenized="true">test test > 14</custom-tag>
Input
Code
var defaultXmlOptions = {
ignoreAttributes: false,
attributeNamePrefix: "@_",
indentBy: " ",
textNodeName: "#text",
format: true,
},
var testJson = { component: {
"custom-tag": {
"#text": "test test > 14",
"@_tokenized": true
}
}}
Here is the code that converts:
var parser = new XMLBuilder(defaultXmlOptions);
var xml = parser.build(testJson);
Output
<component>
<custom-tag tokenized>test test > 14</custom-tag>
</component>
That attribute should have ="true"
Expected Output
<component>
<custom-tag tokenized="true">test test > 14</custom-tag>
</component>
Old Code that used to work
var Parser = require("fast-xml-parser").j2xParser;
var parser = new Parser(defaultXmlOptions);
var xml = parser.parse(testJson);
Now converting my Project from CRA to Vite can’t use require.
2
Answers
What you are missing is the option
suppressBooleanAttributes
in the XMLBuilder. By default, boolean attributes liketrue
will have its value omitted in the built XML.Set
suppressBooleanAttributes
tofalse
.You could also use
attributeValueProcessor
. In fact, simply doing:would print the value, but if you don’t need to do anything interesting there,
suppressBooleanAttributes
is your best option.