如何在Erlang中将XML转换为元组列表?

ivqmmu1c  于 2023-09-28  发布在  Erlang
关注(0)|答案(1)|浏览(144)

我正在尝试从XML中创建键、值对元组。我想用任何嵌套的XML做一个列表。这似乎是一个很常见的事情,但我找不到任何例子。
例如:

<something>
        <Item>
            <name>The Name!</name>
            <reviews>
                    <review>
                        <review-by>WE</review-by>
                        <review-points>92</review-points>
                    </review>
        
                    <review>
                        <review-by>WS</review-by>
                        <review-points>90</review-points>
                    </review>
            </reviews>
        </Item>
    </something>

结果应该是:

[[{"name", "The Name!"}, {"reviews", [{"review-by", "WE"}, {"review-points", 92}], {"review-by", "WS"}, {"review-points", 90}]} ]]

其中每个Item都是主 Package 器节点。
我承认货物邪教和调整下面的代码。它只返回第一个Item元素的列表。我不知道如何开始嵌套的。

-module(reader).
    -compile(export_all).
    -include_lib("xmerl/include/xmerl.hrl").

    parse(FileName) ->
        {Records,_} = xmerl_scan:file(FileName),
        extract(Records, []).
    
    extract(Record, Acc) when is_record(Record, xmlElement) ->
        case Record#xmlElement.name of
            'Item' ->
                ItemData = lists:foldl(fun extract/2, [], Record#xmlElement.content),
                [ {item, ItemData} | Acc ];
            _ ->
                lists:foldl(fun extract/2, Acc, Record#xmlElement.content)
        end;

    extract({xmlText, [{Attribute, _}, {'Item', 2}, _], _, _, Value, text}, Acc) ->
        [{Attribute, Value}|Acc];
    
    extract(_, Acc) ->
        Acc.
jw5wzhpr

jw5wzhpr1#

Erlsom试试函数“erlsom:simple_form(XML)”将为您提供{Node,Attrib,Value}:

{"something",[],
 [{"Item",[],
   [{"name",[],["The Name!"]},
    {"reviews",[],
     [{"review",[],
       [{"review-by",[],["WE"]},{"review-points",[],["92"]}]},
      {"review",[],
       [{"review-by",[],["WS"]},{"review-points",[],["90"]}]}]}]}]}

但是,如果您想删除Attributes,那么您可以编写一个有趣的函数传递给erlsom SAX解析器,或者重新格式化simple_form的输出。类似这样的东西(重新格式化输出):

-module(reader).
-compile(export_all).

convert(XML)->
    case erlsom:simple_form(XML) of
        {ok,{Node,_Attrib,Value},_}->
            {Node,xml_to_kv(Value)};
        Err->
            Err
    end.

xml_to_kv([{Node,_Attrib,Value}|T])->
    [{Node,lists:flatten(xml_to_kv(Value))}|xml_to_kv(T)];

xml_to_kv(Value)->
    Value.

这将产生以下输出:

{"something",
 [{"Item",
   [{"name","The Name!"},
    {"reviews",
     [{"review",[{"review-by","WE"},{"review-points","92"}]},
      {"review",[{"review-by","WS"},{"review-points","90"}]}]}]}]}

注意,我还没有在非常大的XML文件上测试过这个方法。您应该运行一些测试并考虑内存问题。

相关问题