解出xml Str字段 Str:查找字段 XmlStr:xml格式的string
string(Str, XmlStr) ->
{Doc, _} = xmerl_scan:string(XmlStr),
Date = xmerl_xpath:string(Str, Doc),
if
Date =/= [] ->
[#xmlElement{content = Content}] = Date,
[#xmlText{value = Val}] = Content,
Val;
true ->
""
end.
文件解出xml Str字段 Str:查找字段 XmlFile:xml文件位置
file(Str, XmlFile) ->
{Doc, _} = xmerl_scan:file(XmlFile),
Date = xmerl_xpath:string(Str, Doc),
if
Date =/= [] ->
[#xmlElement{content = Content}] = Date,
[#xmlText{value = Val}] = Content,
Val;
true ->
""
end.
文件解出xml Str字段转为列表形式 XmlFile:文件位置
decode_file(XmlFile) ->
{Doc, _} = xmerl_scan:file(XmlFile),
Content = decode_handler(Doc),
lists:foldl(
fun(#xmlText{pos = Pos, parents = Parents, value = Value}, TextL1) ->
{Key, _} = lists:nth(Pos, Parents),
[{Key, Value} | TextL1]
end, [], Content).
转成xml 转为列表形式 Xml:xml格式的string
decode(Xml) ->
ContentList = decode_shift(util:to_list(Xml), []),
TextL =
lists:foldl(
fun(#xmlText{pos = Pos, parents = Parents, value = Value}, TextL1) ->
{Key, _} = lists:nth(Pos, Parents),
[{Key, Value} | TextL1]
end, [], ContentList),
TextL.
%% 转换内容的解析内容
decode_shift("", L) ->
L;
decode_shift(Xml, L) ->
{Doc, Doc1} = xmerl_scan:string(Xml),
Content = decode_handler(Doc),
decode_shift(Doc1, Content ++ L).
处理内容的解析内容
decode_handler(Element) ->
lists:flatten(decode_handler(Element, [])).
decode_handler(Element, L) ->
case Element of
#xmlText{pos = 1} ->
[Element | L];
#xmlElement{content = Content1} ->
decode_handler(Content1, []) ++ L;
ElementList when is_list(ElementList) ->
[decode_handler(Element1, []) || Element1 <- ElementList];
_ ->
L
end.
列表 转成xml 格式:List=[{key,value}|...]
encode(List) ->
ParamList = encode_handler(List, []),
XmlList = xmerl:export_simple_content(ParamList, xmerl_xml),
"<xml>" ++ lists:flatten(XmlList) ++ "</xml>".
encode_handler([], L) ->
L;
encode_handler([{Key, Value} | List], L) ->
NewValue =
case is_list(Value) of
true ->
case hd(Value) of
{_, _} ->
encode_handler(Value, []);
_ ->
case is_change_list(Value) of
false ->
io_lib:format("~p", [Value]);
_ ->
[Value]
end
end;
_ ->
[util:to_list(Value)]
end,
encode_handler(List, [{util:to_atom(Key), NewValue} | L]).
is_change_list([]) ->
true;
is_change_list([S | Str]) ->
case is_integer(S) of
true ->
is_change_list(Str);
_ ->
false
end.
方法只是平时工作时处理的,如果有不同见解,请留言讨论