node.js – Change value of an xml element using a field identifier

I am currently trying to understand how to parse xml with the use of nodejs xml2js. I have an example xml pasted below. I am able to do a simple read of this xml with the code shown below. However, my end goal is to get this into a json format where I can modify/update the user value from test to something_else and then convert back to xml. The xml document can vary and have multiple fields. What would be the best way to make the xml a json, identify a field by its id, then change it’s value and convert back to xml?


<xml xmlns="" collection="false">
    <variable type="" id="4XRmU5fIz]ZHw3:5|iwK">User</variable>
  <block type="trade" id="xgH69|xFn9=70w.*3Vo@" x="0" y="0">
    <statement name="INITIALIZATION">
        <block type="variables_set" id="Kw~OPnp?E`1]c;Uvrtc^">
            <field name="VAR" id="4XRmU5fIz]ZHw3:5|iwK" variabletype="">User</field>
            <value name="VALUE">
                <block type="text" id="OYG-g2~DojhZ-=5[3I!W">
                <field name="TEXT">Test</field>


var xml2js = require('xml2js');
var xml = fs.readFileSync(`./test.xml`, {
    encoding: "utf-8",

const xmlParser = new xml2js.Parser({ cdata: true });
const sampleJSON = xmlParser.parseStringPromise(xml);
console.log("jsonData", sampleJSON);

Read more here: Source link