【问题标题】:Parsing XML websocket responses with Strophe.js使用 Strophe.js 解析 XML websocket 响应
【发布时间】:2019-09-25 03:06:30
【问题描述】:

我正在使用 Strophe.js 通过 websockets 连接到 XMPP 服务器。以下是连接用户收到消息时收到的示例响应:

<message xmlns='jabber:client' xml:lang='en' to='agent@chat.domain.com/6665193359253278721998' from='client@chat.domain.com/Mac' type='chat' id='purple42fccc5c'> 
  <archived by='agent@chat.domain.com' id='1557026681122740' xmlns='urn:xmpp:mam:tmp'/>
  <stanza-id by='agent@chat.domain.com' id='1557026681122740' xmlns='urn:xmpp:sid:0'/>
  <active xmlns='http://jabber.org/protocol/chatstates'/> 
  <body>
    1
  </body>
</message>

检查了文档,但我找不到关于该主题的任何有用信息。 Strophe 是否具有从不同类型的消息中提取我需要的数据的内置方法?还是我需要别的东西?

【问题讨论】:

  • 不知道内置插件,但您可以使用 DOMParser 将 xml 字符串解析为 xml 文档。然后,您可以使用通常的 .getElementById() 等或 xpath 与 XML 交互。如果可能的话,更喜欢 JSON 而不是 XML 作为消息格式,因为它更小更容易交互。

标签: javascript xml xmpp ejabberd strophe


【解决方案1】:

创建连接后,您需要定义挂钩来接收消息并能够与之交互:

connection.addHandler(onMessage, null, 'message', 'chat');
connection.addHandler(onMessage, null, 'message', 'groupchat');

然后,您只需要定义onMessage 函数。

onMessge: function(stanza) {
  $stanza = $(stanza);

  messageId = $stanza.attr('id') || null;
  to = $stanza.attr('to');
  from = $stanza.attr('from').toLowerCase();
  barejid = Strophe.getBareJidFromJid(from);

  type = $stanza.attr('type');
  bodies = $stanza.find('body');
  body = bodies.length ? Strophe.xmlunescape(Strophe.getText(bodies[0])) : '';
....

}

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    相关资源
    最近更新 更多