Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
xmerl elixir snippet
event = fn
{:startElement, _, 'Contents', _, _}, _, state ->
put_in(state[:current], %{})
{:startElement, _, _name, _, _}, _, state ->
put_in(state[:value], "")
{:characters, data}, _, state ->
update_in(state[:value], &(to_string(data) <> &1))
{:endElement, _, 'Contents', _}, _, state ->
%{state | :current => nil, :contents => [state[:current] | state[:contents]}
{:endElement, _, name, _}, _, state = %{current: current} when is_map(current) ->
put_in(state, [:current, to_string(name)], state[:value])
{:endElement, _, 'ListBucketResult', _}, _, state ->
state
{:endElement, _, name, _}, _, state ->
put_in(state, [:response, to_string(name)], state[:value])
_, _, state -> state
end
format = fn {:ok, %{response: r, contents: c}, _} -> Dict.put(r, "Contents", Enum.reverse(c)) end
File.read!("sample.xml")
|> :xmerl_sax_parser.stream(event_fun: event, event_state: %{response: %{}, contents: []})
|> format.()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment