Skip to content

Instantly share code, notes, and snippets.

@bcardarella
Created December 6, 2014 20:09
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 bcardarella/6fb8250e77dd9c5ff2f0 to your computer and use it in GitHub Desktop.
Save bcardarella/6fb8250e77dd9c5ff2f0 to your computer and use it in GitHub Desktop.
defmodule Weather do
require Record
Record.defrecord :xmlElement, Record.extract(:xmlElement, from_lib: "xmerl/include/xmerl.hrl")
Record.defrecord :xmlText, Record.extract(:xmlText, from_lib: "xmerl/include/xmerl.hrl")
def parse_url(url) do
{:ok, response} = HTTPoison.get(url)
{ xml, _rest} = :xmerl_scan.string :erlang.bitstring_to_list(response.body)
nodes = :xmerl_xpath.string('/current_observation/*', xml)
{ response, xml, nodes }
end
def parse_nodes(nodes) do
Enum.reduce nodes, Map.new, fn(node, accum) ->
name = Atom.to_string(node.name)
[text_node] = node.content
Map.put(accum, name, text_node.value)
end
end
def build_map_from(url) do
{_response, _xml, nodes} = parse_url(url)
parse_nodes(nodes)
end
end
Weather.build_map_from("http://w1.weather.gov/xml/current_obs/KDTO.xml")
# => ** (UndefinedFunctionError) undefined function: :xmlElement.name/1 (module :xmlElement is not available)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment