2002-11-18 21:39:47 +01:00
|
|
|
%%%----------------------------------------------------------------------
|
|
|
|
%%% File : xml_stream.erl
|
|
|
|
%%% Author : Alexey Shchepin <alexey@sevcom.net>
|
|
|
|
%%% Purpose :
|
|
|
|
%%% Created : 17 Nov 2002 by Alexey Shchepin <alexey@sevcom.net>
|
|
|
|
%%% Id : $Id$
|
|
|
|
%%%----------------------------------------------------------------------
|
|
|
|
|
|
|
|
-module(xml_stream).
|
|
|
|
-author('alexey@sevcom.net').
|
|
|
|
-vsn('$Revision$ ').
|
|
|
|
|
|
|
|
-export([start/1, init/1, send_text/2]).
|
|
|
|
|
2003-10-20 20:23:30 +02:00
|
|
|
-define(XML_START, 0).
|
|
|
|
-define(XML_END, 1).
|
|
|
|
-define(XML_CDATA, 2).
|
|
|
|
-define(XML_ERROR, 3).
|
|
|
|
|
2002-11-18 21:39:47 +01:00
|
|
|
start(CallbackPid) ->
|
|
|
|
spawn(?MODULE, init, [CallbackPid]).
|
|
|
|
|
|
|
|
init(CallbackPid) ->
|
|
|
|
Port = open_port({spawn, expat_erl}, [binary]),
|
|
|
|
loop(CallbackPid, Port, []).
|
|
|
|
|
|
|
|
loop(CallbackPid, Port, Stack) ->
|
|
|
|
receive
|
|
|
|
{Port, {data, Bin}} ->
|
|
|
|
Data = binary_to_term(Bin),
|
|
|
|
loop(CallbackPid, Port, process_data(CallbackPid, Stack, Data));
|
2003-10-20 20:23:30 +02:00
|
|
|
{_From, {send, Str}} ->
|
2002-11-18 21:39:47 +01:00
|
|
|
Port ! {self(), {command, Str}},
|
|
|
|
loop(CallbackPid, Port, Stack)
|
|
|
|
end.
|
|
|
|
|
|
|
|
process_data(CallbackPid, Stack, Data) ->
|
|
|
|
case Data of
|
2003-10-20 20:23:30 +02:00
|
|
|
{?XML_START, {Name, Attrs}} ->
|
2002-11-18 21:39:47 +01:00
|
|
|
if Stack == [] ->
|
|
|
|
gen_fsm:send_event(CallbackPid,
|
|
|
|
{xmlstreamstart, Name, Attrs});
|
|
|
|
true -> true
|
|
|
|
end,
|
|
|
|
[{xmlelement, Name, Attrs, []} | Stack];
|
2003-10-20 20:23:30 +02:00
|
|
|
{?XML_END, EndName} ->
|
2002-11-18 21:39:47 +01:00
|
|
|
case Stack of
|
|
|
|
[{xmlelement, Name, Attrs, Els} | Tail] ->
|
|
|
|
NewEl = {xmlelement, Name, Attrs, lists:reverse(Els)},
|
|
|
|
Len = length(Tail),
|
|
|
|
if
|
|
|
|
Len > 1 -> add_subelement(NewEl, Tail);
|
|
|
|
Len == 1 ->
|
|
|
|
gen_fsm:send_event(CallbackPid,
|
|
|
|
{xmlstreamelement, NewEl}),
|
|
|
|
Tail;
|
|
|
|
Len == 0 ->
|
|
|
|
gen_fsm:send_event(CallbackPid,
|
|
|
|
{xmlstreamend, EndName}),
|
|
|
|
Tail
|
|
|
|
end
|
|
|
|
end;
|
2003-10-20 20:23:30 +02:00
|
|
|
{?XML_CDATA, CData} ->
|
2002-11-18 21:39:47 +01:00
|
|
|
add_subelement({xmlcdata, CData}, Stack);
|
2003-10-20 20:23:30 +02:00
|
|
|
{?XML_ERROR, Err} -> gen_fsm:send_event(CallbackPid,
|
|
|
|
{xmlstreamerror, Err})
|
2002-11-18 21:39:47 +01:00
|
|
|
end.
|
|
|
|
|
|
|
|
|
|
|
|
add_subelement(El, Stack) ->
|
|
|
|
case Stack of
|
|
|
|
[{xmlelement, Name, Attrs, Els} | Tail] ->
|
|
|
|
[{xmlelement, Name, Attrs, [El | Els]} | Tail];
|
|
|
|
[] -> []
|
|
|
|
end.
|
|
|
|
|
|
|
|
|
|
|
|
send_text(Pid, Text) ->
|
|
|
|
Pid ! {self(), {send, Text}}.
|
|
|
|
|