Skip to content

Instantly share code, notes, and snippets.

@fcheung
Created October 28, 2014 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcheung/d3ff215e88334dd7542a to your computer and use it in GitHub Desktop.
Save fcheung/d3ff215e88334dd7542a to your computer and use it in GitHub Desktop.
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