skip to Main Content

fast-xml-parser version 4.3.6

Description

I need to include xml attribute (tokenized="true"), like this : <custom-tag tokenized="true">test test &gt; 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 &gt; 14</custom-tag>
</component>

That attribute should have ="true"

Expected Output

<component>
  <custom-tag tokenized="true">test test &gt; 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


  1. What you are missing is the option suppressBooleanAttributes in the XMLBuilder. By default, boolean attributes like true will have its value omitted in the built XML.

    function demo() {
      var defaultXmlOptions = {
        ignoreAttributes: false,
        attributeNamePrefix: "@_",
        indentBy: "  ",
        textNodeName: "#text",
        format: true,
        // You need this to preserve boolean values!
        suppressBooleanAttributes: false,
      };
      var testJson = {
        component: {
          "custom-tag": {
            "#text": "test test > 14",
            "@_tokenized": true
          }
        }
      };
    
      var parser = new XMLBuilder(defaultXmlOptions);
      var xml = parser.build(testJson);
      console.log(xml);
    }
    
    document.addEventListener("readystatechange", () => document.readyState === "complete" && demo());
    <script type="module">
      import { XMLBuilder } from 'https://cdn.jsdelivr.net/npm/[email protected]/+esm';
      window.XMLBuilder = XMLBuilder;
    </script>
    Login or Signup to reply.
  2. Set suppressBooleanAttributes to false.

    You could also use attributeValueProcessor. In fact, simply doing:

    attributeValueProcessor: (value, attrName) => {
      return value;
    }
    

    would print the value, but if you don’t need to do anything interesting there, suppressBooleanAttributes is your best option.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search