Created
October 28, 2014 10:32
-
-
Save fcheung/d3ff215e88334dd7542a to your computer and use it in GitHub Desktop.
xmerl elixir snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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