编辑代码

-module(xml_extractor).
-include_lib("xmerl/include/xmerl.hrl").
-export([extract_data/1, main/1]).

%% 提取 XML 字符串中的特定元素值
extract_data(XmlStr) ->
    {XmlDoc, _} = xmerl_scan:string(XmlStr),
    extract_from_element(XmlDoc).

%% 递归遍历 XML 元素并提取数据
extract_from_element(#xmlElement{name = Name, content = Content}) ->
    case Name of
        'quick_message' ->
            extract_message(Content);
        _ ->
            []
    end.

%% 提取 message 元素中的所有子元素
extract_message(Content) ->
    lists:foldl(fun extract_element/2, #{}, Content).

%% 提取单个元素
extract_element(#xmlElement{name = Name, content = [#xmlText{value = Value}]}, Acc) ->
    maps:put(Name, Value, Acc);
extract_element(_, Acc) ->
    Acc.

%% 主函数
main(_) ->
    XmlData = <<
        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
        "<quick_message>\n"
        "    <message>\n"
        "        <uid>50848343</uid>\n"
        "        <login_name>GG366822889</login_name>\n"
        "        <out_order_no>13420170114150053861611313</out_order_no>\n"
        "        <order_no>0720170114150059110833</order_no>\n"
        "        <pay_time>2017-01-14 15:01:17</pay_time>\n"
        "        <amount>0.01</amount>\n"
        "        <status>0</status>\n"
        "        <extras_params>13420170114150053861611313</extras_params>\n"
        "    </message>\n"
        "</quick_message>"
    >>,
    Data = extract_data(XmlData),
    io:format("UID: ~p~n", [maps:get(uid, Data)]),
    io:format("Login Name: ~p~n", [maps:get(login_name, Data)]),
    io:format("Out Order No: ~p~n", [maps:get(out_order_no, Data)]),
    io:format("Order No: ~p~n", [maps:get(order_no, Data)]),
    io:format("Pay Time: ~p~n", [maps:get.pay_time, Data)]),
    io:format("Amount: ~p~n", [maps:get(amount, Data)]),
    io:format("Status: ~p~n", [maps:get(status, Data)]),
    io:format("Extras Params: ~p~n", [maps:get(extras_params, Data)]).