简体   繁体   English

从XML对象检索数据

[英]Retrieve data from XML Object

I'm having a small problem. 我有一个小问题。 I parsed an message with an xml2js Parser 我用xml2js解析器解析了一条消息

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: 正确返回一个XML对象,如下所示:

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

but know i want the data, meaning type = authMessage; 但是知道我想要数据,意思是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. 使用parser.parseString() ,您将获得一个普通的Javascript对象。 How about: 怎么样:

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

Here is some documentation on Javascript variable types. 这是一些有关Javascript变量类型的文档。

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; 在异步回调中显示结果,该回调 return value; 之后执行return value; . So value is not initialized and function returns undefined . 因此, value未初始化,函数返回undefined

This code may work if parseString does not perform asynchronous calls internally but it is an exceptional situation. 如果parseString不在内部执行异步调用,则此代码可能有效,但这是一种例外情况。 Most of the code with callbacks works asynchronously. 大多数带有回调的代码都是异步工作的。 So you need to organize your code in this manner too. 因此,您也需要以这种方式来组织代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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