简体   繁体   中英

Retrieve data from XML Object

I'm having a small problem. I parsed an message with an xml2js Parser

parser.parseString(message.toString(), function (err,result) {
    //Extract the value from the data element
    value = result;
    console.log(result);
});
return value;

This correctly returns an XML object which looks like:

{message: { type: ['authMessage'], sender: ['username']} }

but know i want the data, meaning type = authMessage; sender = username;

How can i get that data? I'm not really sure, thanks for any help.

Once you've used parser.parseString() , you get a plain Javascript object. How about:

var type = result.message.type[0];
var sender = result.message.sender[0];

Here is some documentation on Javascript variable types.

It looks like you are not well aware of "asynchronous" and "synchronous" concepts. console.log(result); displays the result in the asynchronous callback, which is executed after return value; . So value is not initialized and function returns undefined .

This code may work if parseString does not perform asynchronous calls internally but it is an exceptional situation. Most of the code with callbacks works asynchronously. So you need to organize your code in this manner too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM