1 |
|
%%============================================================================== |
2 |
|
%% Copyright 2014 Erlang Solutions Ltd. |
3 |
|
%% |
4 |
|
%% Licensed under the Apache License, Version 2.0 (the "License"); |
5 |
|
%% you may not use this file except in compliance with the License. |
6 |
|
%% You may obtain a copy of the License at |
7 |
|
%% |
8 |
|
%% http://www.apache.org/licenses/LICENSE-2.0 |
9 |
|
%% |
10 |
|
%% Unless required by applicable law or agreed to in writing, software |
11 |
|
%% distributed under the License is distributed on an "AS IS" BASIS, |
12 |
|
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 |
|
%% See the License for the specific language governing permissions and |
14 |
|
%% limitations under the License. |
15 |
|
%%============================================================================== |
16 |
|
-module(mongoose_api_xml). |
17 |
|
|
18 |
|
-behaviour(mongoose_api_format). |
19 |
|
|
20 |
|
-export([serialize/1, deserialize/1]). |
21 |
|
|
22 |
|
-include("mongoose.hrl"). |
23 |
|
-include_lib("exml/include/exml.hrl"). |
24 |
|
|
25 |
|
%%-------------------------------------------------------------------- |
26 |
|
%% mongoose_api_format callbacks |
27 |
|
%%-------------------------------------------------------------------- |
28 |
|
serialize(Data) -> |
29 |
:-( |
do_serialize(Data). |
30 |
|
|
31 |
|
deserialize(IOList) -> |
32 |
:-( |
{ok, ParsedXML} = exml:parse(iolist_to_binary([IOList])), |
33 |
:-( |
ParsedXML. |
34 |
|
|
35 |
|
%%-------------------------------------------------------------------- |
36 |
|
%% internal functions |
37 |
|
%%-------------------------------------------------------------------- |
38 |
|
do_serialize(Data) -> |
39 |
:-( |
exml:to_iolist(prepare_xmlel(Data)). |
40 |
|
|
41 |
|
prepare_xmlel(List) when is_list(List) -> |
42 |
:-( |
prepare_xmlel({<<"list">>, List}); |
43 |
|
prepare_xmlel({ElementName, List}) when is_list(List) -> |
44 |
:-( |
{Attrs, Children} = lists:partition(fun is_attribute/1, List), |
45 |
:-( |
#xmlel{name = to_iolist_compliant(ElementName), |
46 |
:-( |
attrs = [prepare_xmlel(Attr) || Attr <- Attrs], |
47 |
:-( |
children = [prepare_xmlel(Child) || Child <- Children]}; |
48 |
|
prepare_xmlel({Key, Value}) -> |
49 |
:-( |
{to_iolist_compliant(Key), to_iolist_compliant(Value)}; |
50 |
|
prepare_xmlel(Other) -> |
51 |
:-( |
#xmlel{name = to_iolist_compliant(Other)}. |
52 |
|
|
53 |
|
is_attribute({_, List}) when is_list(List) -> |
54 |
:-( |
false; |
55 |
|
is_attribute({_, _}) -> |
56 |
:-( |
true; |
57 |
|
is_attribute(_) -> |
58 |
:-( |
false. |
59 |
|
|
60 |
|
to_iolist_compliant(Atom) when is_atom(Atom) -> |
61 |
:-( |
atom_to_binary(Atom, utf8); |
62 |
|
to_iolist_compliant(Int) when is_integer(Int) -> |
63 |
:-( |
integer_to_binary(Int); |
64 |
|
to_iolist_compliant(Other) -> |
65 |
:-( |
Other. |