mysql result to xml then to iq

Hi,

I am working on simple module to get 3 fields from database but i am not sure how to place it to IQ. I tried several options

MysqlResult = {selected,["id","first_name","last_name"],
         [{1,"Matt","Williamson"},
         {2,"Matt","Williamson2"}]}

how to make it look like :

XML = "
<result id='1'>
<first_name>Matt</first_name>
<last_name>Williamson</last_name>
</result>
<result id='2'>
<first_name>Matt</first_name>
<last_name>Williamson2</last_name>
</result>"

I am looking for a smart way for placing it into IQ ( ejabberd )

IQ#iq{type = result, sub_el =
                   [{xmlelement, "result",
                   [{"xmlns", ?NS_NAMES}],
                   [{xmlelement, "userinfo", [],
                   [{xmlcdata,"???"??  }]}]}]}

Thanks,

I wrote this small module.

I wrote this small module. Copy the functions you want from here:

-module(testm).
-export([test/0]).

-include("ejabberd.hrl").
-include("jlib.hrl").

-define(NS_NAMES, "test-names").

%%%
%%% Convert a Mysql result into IQ result
%%%

make_iq(MysqlResult) ->
    ResultXmls = make_results(MysqlResult),
    #iq{type = result, sub_el =
	    [{xmlelement, "result", [{"xmlns", ?NS_NAMES}],
		    [{xmlelement, "userinfo", [], ResultXmls}]}]}.

make_results({selected, ["id", "first_name", "last_name"], Items}) ->
    [make_result(Item) || Item <- Items].

make_result({Id, First, Last}) ->
    SubEls = [
	{xmlelement, "first_name", [], [{xmlcdata, First}]},
	{xmlelement, "last_name", [], [{xmlcdata, Last}]}
    ],
    {xmlelement, "result", [{"id", integer_to_list(Id)}], SubEls}.

%%%
%%% Test code
%%%

test() ->
    MysqlResult = test_input(),
    IQXml = make_iq(MysqlResult),
    IQString = xml:element_to_string(jlib:iq_to_xml(IQXml)),
    ?INFO_MSG("IQ built: ~n~s~n~nDesired result:~n~s",
	[IQString, test_wanted()]),
    test_finished.

test_input() ->
    {selected,["id","first_name","last_name"],
         [{1,"Matt","Williamson"},
         {2,"Matt","Williamson2"}]}.

test_wanted() ->
    "<result id='1'>
	<first_name>Matt<first_name>
        <last_name>Williamson<last_name>
    <result>
    <result id='2'>
	<first_name>Matt<first_name>
	<last_name>Williamson2<last_name>
    <result>".

This is the result I get when I run the test/0 function:

(ejabberd@localhost)1> testm:test().
test_finished

=INFO REPORT==== 30-Mar-2011::19:08:11 ===
I(<0.43.0>:testm:37) : IQ built:
<iq type='result'><result xmlns='test-names'><userinfo><result id='1'><first_name>Matt<first_name>
<last_name>Williamson<last_name><result><result id='2'><first_name>Matt<first_name>
<last_name>Williamson2<last_name><result><userinfo><result><iq>

Desired result:
<result id='1'>
        <first_name>Matt<first_name>
        <last_name>Williamson<last_name>
    <result>
    <result id='2'>
        <first_name>Matt<first_name>
        <last_name>Williamson2<last_name>
    <result>
Syndicate content