Add XML-parsing and nicely format output
thank you @ pspdfkit to show me how to use XM(ER)L-stuff from erlang :-) Feels like using Swift in combination with ObjC
This commit is contained in:
parent
279688eb1e
commit
27d91f821a
|
@ -0,0 +1,23 @@
|
|||
defmodule Weather.NiceXMLFormatter do
|
||||
require Weather.XML
|
||||
|
||||
def format_observation_nicely(xml_string) when is_binary(xml_string) do
|
||||
{doc, []} =
|
||||
xml_string
|
||||
|> to_charlist()
|
||||
|> :xmerl_scan.string()
|
||||
|
||||
location = get_child("location", doc)
|
||||
weather = get_child("weather", doc)
|
||||
observation_time = get_child("observation_time", doc)
|
||||
|
||||
IO.puts "Location: #{location}"
|
||||
IO.puts "Weather: #{weather}"
|
||||
IO.puts observation_time
|
||||
end
|
||||
|
||||
defp get_child(node_name, doc) do
|
||||
:xmerl_xpath.string('/current_observation/#{node_name}/text()', doc)
|
||||
|> Enum.map(&Weather.XML.xmlText(&1, :value))
|
||||
end
|
||||
end
|
|
@ -0,0 +1,9 @@
|
|||
# thank you PSPDFKit-people: https://pspdfkit.com/blog/2018/how-to-parse-xml-documents-in-elixir/
|
||||
|
||||
defmodule Weather.XML do
|
||||
import Record
|
||||
|
||||
defrecord(:xmlElement, extract(:xmlElement, from_lib: "xmerl/include/xmerl.hrl"))
|
||||
defrecord(:xmlAttribute, extract(:xmlAttribute, from_lib: "xmerl/include/xmerl.hrl"))
|
||||
defrecord(:xmlText, extract(:xmlText, from_lib: "xmerl/include/xmerl.hrl"))
|
||||
end
|
|
@ -14,7 +14,7 @@ defmodule Weather.MixProject do
|
|||
# Run "mix help compile.app" to learn about applications.
|
||||
def application do
|
||||
[
|
||||
extra_applications: [:logger, :httpoison]
|
||||
extra_applications: [:logger, :httpoison, :xmerl]
|
||||
]
|
||||
end
|
||||
|
||||
|
|
Loading…
Reference in New Issue