Search code examples
erlangxmpptuplesejabberderlang-shell

ERLANG Convert String to List of Tuples


I have a String of usernames in the form of "hello1@devlab, hello2@devlab, hello3@devlab" This String can have N number of usernames.

I want to convert this into a Packet of the form:

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!">>}],[]}
]
}]},

Accordingly this packet should be able to accomadate N number of usernames [according to the number of usernames in the String], by adding extra xmlel Tuples like this:-

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!">>}],[]}
]
}]},

How can I achieve this??

Thanks & Regards


Solution

  • Here is an example how to convert your string to a list of address:

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

    So a list of addresses for your packet can be generated from Addrs like this:

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