xml 파일을 저장하기위해 다음과 같은 함수를 만들었다.
save_xml(Path, RootEl) ->
{ok,IOF}=file:open(Path,[write]),
Export=xmerl:export_simple([RootEl], xmerl_xml),
io:format(IOF,"~s~n", [lists:flatten(Export)]),
file:close(IOF).
에러가 났다.
83> foo:save_xml("/tmp/foo.xml", Root).
** exception exit: {badarg,[{io,format,
[<0.3348.0>,"~s~n",
[[60,63,120,109,108,32,118,101,114,115,105,
111,110,61,34,49,46,48,34|...]]]},
{erl_eval,do_apply,5},
{shell,exprs,6},
{shell,eval_exprs,6},
{shell,eval_loop,3}]}
in function io:o_request/2
이거 분명히 예전에 공부할 때 예제가 동작하는 것을 확인한 함수였는데....
binary로 써보기로했다.
84> Export=xmerl:export_simple([Root], xmerl_xml).
........
85> file:write_file("/tmp/1.xml", list_to_binary(lists:flatten(Export))).
** exception error: bad argument
in function list_to_binary/1
called as list_to_binary([60,63,120,109,108,32,118,101,114,115,105,
111,110,61,34,49,46,48,34,63,62,60,111,108,
100,114,103,112|...])
한글이 포함되어 안되는 것으로 짐작이 갔다.
99> list_to_binary([0, 1, 2]).
<<0,1,2>>
100> list_to_binary([0, 1, 2, 255]).
<<0,1,2,255>>
101> list_to_binary([0, 1, 2, 255, 256]).
** exception error: bad argument
in function list_to_binary/1
called as list_to_binary([0,1,2,255,256])
결론은
list_to_binary가 255를 넘어가는 non-ascii를 제대로 처리하지 못해서였다.
102> list_to_binary(xmerl_ucs:to_utf8([0, 1, 2, 255, 256])).
<<0,1,2,195,191,196,128>>
103> file:write_file("/tmp/1.xml", list_to_binary(xmerl_ucs:to_utf8(lists:flatten(Export)))).
ok
맨 처음 함수는 이런 식으로 변경:
save_xml(Path, RootEl) ->
{ok,IOF}=file:open(Path,[write]),
Export=xmerl:export_simple([RootEl], xmerl_xml),
io:format(IOF,"~s~n", [xmerl_ucs:to_utf8(lists:flatten(Export))]),
file:close(IOF).
참고:
http://intertwingly.net/blog/2007/09/14/ASCII-ISO-8859-1-UCS-and-Erlanghappy hackin'