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

<xml xmlns="http://www.w3.org/1999/xhtml" collection="false">
  <variables>
    <variable type="" id="4XRmU5fIz]ZHw3:5|iwK">User</variable>
  </variables>
  <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>
                </block>
            </value>
        </block>
    </statement>
  </block>
</xml>

Node

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