ERLANG将字符串转换为元组列表

时间:2015-02-19 06:48:44

标签: erlang xmpp tuples ejabberd erlang-shell

我有一个形式为的用户名字符串      “hello1 @ devlab,hello2 @ devlab,hello3 @ devlab”     这个String可以有N个用户名。

我想将其转换为格式的数据包:

Packet_in_tuple_form={xmlel,<<"message">>,[{<<"id">>,<<"rkX6Q-8">>},{<<"to">>,<<"multicast.devlab">>}],[{xmlel,<<"body">>,[],[{xmlcdata,<<"ABCMSG">>}]},{xmlel,<<"addresses">>,[{<<"xmlns">>,<<"http://jabber.org/protocol/address">>}],
[
{xmlel,<<"address">>,[{<<"type">>,<<"to">>},{<<"jid">>,<<"hello1@devlab">>},{<<"desc">>,<<"description goes here!">>}],[]},
{xmlel,<<"address">>,[{<<"type">>,<<"to">>},{<<"jid">>,<<"hello2@devlab">>},{<<"desc">>,<<"description goes here!">>}],[]},
{xmlel,<<"address">>,[{<<"type">>,<<"to">>},{<<"jid">>,<<"hello3@devlab">>},{<<"desc">>,<<"description goes here!">>}],[]}
]
}]},

相应地,这个数据包应该能够通过添加额外的xmlel元组来实现N个用户名[根据字符串中的用户名数量]: -

Packet_in_tuple_form={xmlel,<<"message">>,[{<<"id">>,<<"rkX6Q-8">>},{<<"to">>,<<"multicast.devlab">>}],[{xmlel,<<"body">>,[],[{xmlcdata,<<"ABCMSG">>}]},{xmlel,<<"addresses">>,[{<<"xmlns">>,<<"http://jabber.org/protocol/address">>}],
[
{xmlel,<<"address">>,[{<<"type">>,<<"to">>},{<<"jid">>,<<"hello1@devlab">>},{<<"desc">>,<<"description goes here!">>}],[]},
{xmlel,<<"address">>,[{<<"type">>,<<"to">>},{<<"jid">>,<<"hello2@devlab">>},{<<"desc">>,<<"description goes here!">>}],[]},
{xmlel,<<"address">>,[{<<"type">>,<<"to">>},{<<"jid">>,<<"hello3@devlab">>},{<<"desc">>,<<"description goes here!">>}],[]},
{xmlel,<<"address">>,[{<<"type">>,<<"to">>},{<<"jid">>,<<"hello4@devlab">>},{<<"desc">>,<<"description goes here!">>}],[]},
{xmlel,<<"address">>,[{<<"type">>,<<"to">>},{<<"jid">>,<<"hello5@devlab">>},{<<"desc">>,<<"description goes here!">>}],[]}
]
}]},

我怎样才能实现这个目标?

谢谢&amp;此致

1 个答案:

答案 0 :(得分:3)

以下是如何将字符串转换为地址列表的示例:

Str = "hello1@devlab, hello2@devlab, hello3@devlab",
Addrs = [I || I <- string:tokens(Str, ", ")].

因此,可以从Addrs生成数据包的地址列表,如下所示:

[{xmlel,<<"address">>,[{<<"type">>,<<"to">>},{<<"jid">>,list_to_binary(JID)},{<<"desc">>,<<"description goes here!">>}],[]} || JID <- Addrs].