Search code examples
erlangejabberderl

ejabberd : How to extract data from xml element


I have this packet :

{xmlelement,"presence", [{"xml:lang","en"}, {"ver","6.00.00"}, {"to", "[email protected]/user"}],
                        [{xmlelement,"c", [{"xmlns", "http://jabber.org/protocol/caps"}, {"node", "http://www.google.com/xmpp/client/caps/"}, {"ver", "eVvrsq8jya/4AZMjFl5BeDKSmg4="}, {"hash","sha-1"}], []},
                        {xmlelement,"nick", [{"xmlns", "http://jabber.org/protocol/nick"}], [{xmlcdata,<<"user">>}]},
                        {xmlelement,"x", [{"xmlns", "http://jabber.org/protocol/muc"}], [{xmlelement,"history", [{"maxstanzas","20"}, {"maxchars","32768"}], []}]}]}

And I want to extract data from : ("maxchars" && "node")

What I'm doing is using functions located in xml.erl but i don't know how to do it .

Example for what I tried :

xml:get_subtag(Packet, "maxchars")

Solution

  • With a recent version of ejabberd (= that is less than 3 years old), you can do as follow.

    I assume packet is binary xmlel record:

    P = {xmlel,<<"presence">>, [{<<"xml:lang">>,<<"en">>}, {<<"ver">>,<<"6.00.00">>}, {<<"to">>, <<"[email protected]/user">>}],
         [{xmlel,<<"c">>, [{<<"xmlns">>, <<"http://jabber.org/protocol/caps">>}, {<<"node">>, <<"http://www.google.com/xmpp/client/caps/">>}, {<<"ver">>, <<"eVvrsq8jya/4AZMjFl5BeDKSmg4=">>}, {<<"hash">>,<<"sha-1">>}], []},
          {xmlel,<<"nick">>, [{<<"xmlns">>, <<"http://jabber.org/protocol/nick">>}], [{xmlcdata,<<"user">>}]},
          {xmlel,<<"x">>, [{<<"xmlns">>, <<"http://jabber.org/protocol/muc">>}], [{xmlel,<<"history">>, [{<<"maxstanzas">>,<<"20">>}, {<<"maxchars">>,<<"32768">>}], []}]}]}.
    

    You can then do:

    X = fxml:get_subtag_with_xmlns(P, <<"x">>, <<"http://jabber.org/protocol/muc">>).                                                                                        
    H = fxml:get_subtag(X, <<"history">>).
    {value, MS} = fxml:get_tag_attr(<<"maxstanzas">>, H).
    {value, MC} = fxml:get_tag_attr(<<"maxchars">>, H).  
    

    MS and MC contains your values:

    MS = <<"20">>
    MC = <<"32768">>