Search code examples
xmlerlangejabberd

Manipulating XML element to get value from Sub-element in Erlang


I have this in Packet:

{xmlelement,"message",
  [{"from", "ddfadfdf.com@54.69.16.10/26526129921433241378891365"},
   {"to", "afdafdfaf.com@54.69.16.10/30014432481433242528199830"}],
    [{xmlelement,"received",
       [{"xmlns",
        "urn:xmpp:receipts"},
        {"id", "018A12FB-0718-4304-87FD-430C59EDB4F9"}],
   []}]}

I just need to get the value of the id attribute under the received XML element.


Solution

  • You can use function xml:get_path_s, asking it to descend into the element called received to get the attribute called id:

    > xml:get_path_s(Packet, [{elem, "received"}, {attr, "id"}]).
    "018A12FB-0718-4304-87FD-430C59EDB4F9"
    

    Note that the question and above solution are for older versions of ejabberd, namely 2.1.x. You can tell the difference because older versions use xmlelement records as in the question, but newer versions use xmlel records instead.

    For newer ejabberd versions, the xml module has been replaced by fxml. The function names are the same, just change the module name:

    fxml:get_path_s(Packet, [{elem, "received"}, {attr, "id"}]).