gpt4 book ai didi

mysql - 如何使用 xmerl (erlang) 将元组列表转换为 XML 格式

转载 作者:行者123 更新时间:2023-11-28 23:51:25 27 4
gpt4 key购买 nike

我开始学习 erlang,但我正在为 erlang 中的数据类型转换而苦苦挣扎。

我有来自 mysql 的响应:

[{message,[{id,"500"}],
[{from_user,"admin@domain"}],
[{to_user,"test@domain"}],
[{txt,"Text message from admin to user"}],
[{created_at,"2015-08-28 17:48:41"}]},
...
{message,[{id,"550"}],
[{from_user,"test@domain"}],
[{to_user,"admin@domain"}],
[{txt,"message from test to admin"}],
[{created_at,"2015-08-28 17:48:42"}]}]

但我需要返回一个 XML (application/xml):

<chat>
<message>
<field name="id">500</field>
<field name="from_user">admin@domain</field>
<field name="to_user">test@domain</field>
<field name="txt">Text message from admin to user</field>
<field name="created_at">2015-08-28 17:48:41</field>
</message>
...
<message>
<field name="id">550</field>
<field name="from_user">test@domain</field>
<field name="to_user">admin@domain</field>
<field name="txt">message from test to admin</field>
<field name="created_at">2015-08-28 17:48:42</field>
</message>
</chat>

我已经关注了这个问题的回复,但它没有用:erlang mysql result to xml.我没有得到这部分:io:format("~s", [v(-1)])

我试着按照这个例子编写代码:Generating XML in Erlang using xmerl

假设响应是:

Fields = [[<<"44">>,<<"admin@domain">>, <<"test@domain">>,<<"message here">>, <<"2015-09-08 10:49:26">>],
[<<"47">>,<<"test@domain">>, <<"admin@domain">>,<<"response to message">>, <<"2015-09-08 10:49:36">>]].

我在我的模块中尝试过的:

-define(xml_prolog, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>").
...

make_xml(Fields) ->
Xml = xmerl:export_simple([xml_simple(Fields)],
xmerl_xml,
[{prolog, ?xml_prolog}]),
unicode:characters_to_binary(Xml).

xml_simple(Fields) ->
{chat, [{message, lists:map(
fun(Entry) ->
conversion(Entry)
end, Fields)}]}.

conversion(List_of_lists) ->
Tmp = lists:map(
fun(E) ->
entries_to_tuple_of_lists(E)
end, List_of_lists),
[ {field, [{id, Id}],
[{from_user, From}],
[{to_user, To}],
[{txt, Body}],
[{created_at, Date}]} || {Id,From,To,Body,Date} <- Tmp].

entries_to_tuple_of_lists(Entries) ->
list_to_tuple(
lists:map(
fun(Elem) ->
bitstring_to_list(Elem)
end, Entries)).

最佳答案

我认为从您的数据示例中更改函数会更容易。结果:

-module(testxml).

-export([makeXml/1]).

-define(xml_prolog, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>").

fields_to_xml_simple2(Fields) ->
[
fun(X) -> [{K, V}] = element(X, Fields), {field, [{name, atom_to_list(K)}], [V]} end(E)
|| E <- lists:seq(2, tuple_size(Fields))].

doc_xml_simple2(Fields) ->
{chat, [{message, fields_to_xml_simple2(K)} || K <- Fields]}.

makeXml(Fields) ->
Xml = xmerl:export_simple([doc_xml_simple2(Fields)], xmerl_xml,
[{prolog, ?xml_prolog}]),
unicode:characters_to_binary(Xml).

关于mysql - 如何使用 xmerl (erlang) 将元组列表转换为 XML 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32510888/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com