Difficulty accessing converted xml child nodes

Hi
I generally work with XML and while I understand what JSON is, reading it is not second nature to me. So I am trying to access a particular child-node within an XML response, without success.

I am using code I nabbed from this thread

    var parseString = require('xml2js').parseString;

    parseString(pm.response.text(), function (err, result) {
        pm.globals.set("xml_parsed_response", JSON.stringify(result));
    });

    let xml_string = pm.globals.get("xml_parsed_response");

    console.log(xml_string);
    pm.globals.set("tranlog_tranid", xml_string.tranlist.trans.TranID);

And I get an error “TypeError | Cannot read property ‘trans’ of undefined”

The value of xml_string is

    {
        "tranlist": {
            "$": {"xmlns:sql": "urn:schemas-microsoft-com:xml-sql"},
            "trans": [
                {
                    "PIUID": ["99999"],
                    "TranID": ["21601"],
                    "DateCreated": ["2019-02-22T16:04:00"],
                    "ByWhom": ["sglOffice"],
                    "DateAmended": ["2019-02-22T16:04:00"],
                    "AmendBy": ["sglOffice"],
                    "What": ["PostmanTest"]
                }
            ]
        }
    }

I am trying to set the value of global ‘tranlog_tranid’ to 21601 in this instance.

Any idea what I am doing wrong?

@crispness parsString is an asynchronous function. In your code, you are expecting it to be synchronously executed. Try this:

var parseString = require('xml2js').parseString;

parseString(pm.response.text(), function (err, result) {
    pm.globals.set("tranlog_tranid", result.tranlist.trans[0].TranID[0]);
});
1 Like

Thanks @prashant_postman

Is there any documentation to go with that library?

@crispness Yes https://www.npmjs.com/package/xml2js