How to convert XML strings to JSON in Erlang?

I want to parse XML strings to erlang list and then to JSON.

Example input:

<?xml version="1.0" encoding="UTF-8"?>
<!--some message here-->
      <number id="333">test message</number>
      <data>current date</data>
      <foo tipo="casa">Some text message 2</foo>

Output should be:

  "start": {
    "data": {
      "number": {
        "@id": "333",
        "#text": "test message"
      "data": "current date"
    "mass": {
      "client": "35",
      "address": "lattitude",
      "code": "3454343",
      "foo": {
        "@tipo": "casa",
        "#text": "Some text message 2"
      "product": "TEST"

I am trying to use erlsom:simple_form(Xml).

and getting :

       [{"number",[{"id","333"}],["test message"]},
        {"data",[],["current date"]}]},
        {"foo",[{"tipo","casa"}],["Some text message 2"]},

Now I want to delete these empty attrs. Is there any simple way to do this? thanks in advance.

UPDATE: Make it work w/ solution from Erlang, converting xml to tuples and lists

BUT Getting

   [{"number","test message"},{"data","current date"}]},
    {"foo","Some text message 2"},

there is no [{"id","333"}] and [{"tipo","casa"}] lists.


  • The output of your simple parsing is in a set format: {Node, Attributes, Children}, so you can write a simple parser that turns that structure you have into a nested proplist. With that, you can either use mochijson or jsx to turn that proplist into a JSON string.

    test() -> parse(data()).
    parse({Node, [], [Value]}) when is_list(Value) ->
        [{Node, Value}];
    parse({Node, [], Children}) ->
        V = children_to_struct(Children, []),
        [{Node, V}];
    parse({Node, Attributes, Children}) ->
        V = attributes_to_struct(Attributes, []) ++ children_to_struct(Children, []),
        [{Node, V}].
    children_to_struct([], Acc) -> Acc;
    children_to_struct([Value], Acc) when is_list(Value) ->
        Acc ++ [{"#text", Value}];
    children_to_struct([Value | T], Acc) when is_tuple(Value) ->
        children_to_struct(T, Acc ++ parse(Value)).
    attributes_to_struct([], Acc) -> Acc;
    attributes_to_struct([{K, V}|T], Acc) ->
        attributes_to_struct(T, Acc ++ [{"@" ++ K, V}]).
    data() ->
           [{"number",[{"id","333"}],["test message"]},
            {"data",[],["current date"]}]},
            {"foo",[{"tipo","casa"}],["Some text message 2"]},

    Running it in the shell with mochijson:

    Eshell V7.3  (abort with ^G)
    1> c(transform).
    2> T = transform:test().
        [{"number",[{"@id","333"},{"#text","test message"}]},
         {"data","current date"}]},
         {"foo",[{"@tipo","casa"},{"#text","Some text message 2"}]},
    4> iolist_to_binary(mochijson2:encode(T)).